text,length,is_long_context,metric_val,label_metric "// ColorMatrix Class v2.6 // // released under MIT License (X11) // http://www.opensource.org/licenses/mit-license.php // // Author: Mario Klingemann // http://www.quasimondo.com /* Copyright (c) 2006-2010 Mario Klingemann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Changes in v1.1: // Changed the RGB to luminance constants // Added colorize() method // Changes in v1.2: // Added clone() // Added randomize() // Added blend() // Added ""filter"" property // Changes in v1.3: // Added invertAlpha() // Added thresholdAlpha() // Changes in v1.4: // Added luminance2Alpha() //Changes in v1.5 // Added rotateX(); // Added rotateY(); // Added rotateZ(); // Added shearZ(); //changes in v2.0 // AS3 optimizations // Added setMultiplicators() // Added clearChannels() // Added rotateHue() // Added transformVector() // Added applyMatrix() // Added rotateRed() // Added rotateGreen() // Added rotateBlue() // Added shearRed() // Added shearGreen() // Added shearBlue() //changes in v2.1 // Added applyColorDeficiency() //changes in v2.2 // Added applyFilter() //changes in v2.3 // Added threshold_rgb() // Added RGB2YUV() // Added YUV2RGB() // Added invertMatrix() // Added normalize() // Added fitRange() // Added toString() // fixed factor in threshold //changes in v2.4 // Added autoDesaturate() //changes in v2.5 // Added extrapolate() //changes in v2.51 // fixed a bug in setChannels // removed some redundand casts from as2 //changes in v2.6 // added tolerance factor to autoDesaturate() // slightly improved performance of autoDesaturate() package com.quasimondo.geom { import flash.display.BitmapData; import flash.filters.ColorMatrixFilter; import flash.geom.Matrix3D; import flash.geom.Point; public class ColorMatrix { public static const COLOR_DEFICIENCY_TYPES:Array = [ 'Protanopia', 'Protanomaly', 'Deuteranopia', 'Deuteranomaly', 'Tritanopia', 'Tritanomaly', 'Achromatopsia', 'Achromatomaly' ]; // Estimatged occurences of color deficiencies: // Protanopia: 1.32% // Protanomaly: 1.32% // Deuteranopia: 1.21% // Deuteranomaly: 5.35% // Tritanopia: 0.031% // Tritanomaly: 0.0002% // Achromatopsia: 0.00002% // Achromatomaly: 0.00002% // RGB to Luminance conversion constants as found on // Charles A. Poynton's colorspace-faq: // http://www.faqs.org/faqs/graphics/colorspace-faq/ private static const LUMA_R:Number = 0.212671; private static const LUMA_G:Number = 0.71516; private static const LUMA_B:Number = 0.072169; // There seem different standards for converting RGB // values to Luminance. This is the one by Paul Haeberli: private static const LUMA_R2:Number = 0.3086; private static const LUMA_G2:Number = 0.6094; private static const LUMA_B2:Number = 0.0820; private static const ONETHIRD:Number = 1 / 3; private static const IDENTITY:Array = [1,0,0,0,0, 0,1,0,0,0, 0,0,1,0,0, 0,0,0,1,0]; private static const RAD:Number = Math.PI / 180; public var matrix:Array; private var tempMatrix:Array; private var preHue:ColorMatrix; private var postHue:ColorMatrix; private var hueInitialized:Boolean; /* Function: ColorMatrix Constructor Parameters: mat - if omitted matrix gets initialized with an identity matrix. Alternatively it can be initialized with another ColorMatrix or an array (there is currently no check if the array is valid. A correct array contains 20 elements.) */ public function ColorMatrix ( mat:Object = null ) { if (mat is ColorMatrix ) { matrix = mat.matrix.concat(); } else if (mat is Array ) { matrix = mat.concat(); } else { matrix = IDENTITY.concat(); } tempMatrix = []; } /* Function: reset resets the matrix to the neutral identity matrix. Applying this matrix to an image will not make any changes to it. Parameters: none Returns: nothing */ public function reset():void { //matrix = IDENTITY.concat(); for ( var i:int = 20; --i > -1; ) matrix[i] = IDENTITY[i]; } public function clone():ColorMatrix { return new ColorMatrix( matrix ); } public function invert():void { concat([ -1 , 0, 0, 0, 255, 0 , -1, 0, 0, 255, 0 , 0, -1, 0, 255, 0, 0, 0, 1, 0]); } /* Function: adjustSaturation changes the saturation Parameters: s - typical values come in the range 0.0 ... 2.0 where 0.0 means 0% Saturation 0.5 means 50% Saturation 1.0 is 100% Saturation (aka no change) 2.0 is 200% Saturation Other values outside of this range are possible -1.0 will invert the hue but keep the luminance Returns: nothing */ public function adjustSaturation( s:Number ):void{ var sInv:Number; var irlum:Number; var iglum:Number; var iblum:Number; sInv = (1 - s); irlum = (sInv * LUMA_R); iglum = (sInv * LUMA_G); iblum = (sInv * LUMA_B); concat([(irlum + s), iglum, iblum, 0, 0, irlum, (iglum + s), iblum, 0, 0, irlum, iglum, (iblum + s), 0, 0, 0, 0, 0, 1, 0]); } /* Function: adjustContrast changes the contrast Parameters: s - typical values come in the range -1.0 ... 1.0 where -1.0 means no contrast (grey) 0 means no change 1.0 is high contrast Returns: nothing */ public function adjustContrast( r:Number, g:Number = NaN, b:Number = NaN ):void { if (isNaN(g)) g = r; if (isNaN(b)) b = r; r += 1; g += 1; b += 1; concat([r, 0, 0, 0, (128 * (1 - r)), 0, g, 0, 0, (128 * (1 - g)), 0, 0, b, 0, (128 * (1 - b)), 0, 0, 0, 1, 0]); } public function adjustBrightness(r:Number, g:Number=NaN, b:Number=NaN):void { if (isNaN(g)) g = r; if (isNaN(b)) b = r; concat([1, 0, 0, 0, r, 0, 1, 0, 0, g, 0, 0, 1, 0, b, 0, 0, 0, 1, 0]); } public function toGreyscale(r:Number, g:Number, b:Number):void { concat([r, g, b, 0, 0, r, g, b, 0, 0, r, g, b, 0, 0, 0, 0, 0, 1, 0]); } public function adjustHue( degrees:Number ):void { degrees *= RAD; var cos:Number = Math.cos(degrees); var sin:Number = Math.sin(degrees); concat([((LUMA_R + (cos * (1 - LUMA_R))) + (sin * -(LUMA_R))), ((LUMA_G + (cos * -(LUMA_G))) + (sin * -(LUMA_G))), ((LUMA_B + (cos * -(LUMA_B))) + (sin * (1 - LUMA_B))), 0, 0, ((LUMA_R + (cos * -(LUMA_R))) + (sin * 0.143)), ((LUMA_G + (cos * (1 - LUMA_G))) + (sin * 0.14)), ((LUMA_B + (cos * -(LUMA_B))) + (sin * -0.283)), 0, 0, ((LUMA_R + (cos * -(LUMA_R))) + (sin * -((1 - LUMA_R)))), ((LUMA_G + (cos * -(LUMA_G))) + (sin * LUMA_G)), ((LUMA_B + (cos * (1 - LUMA_B))) + (sin * LUMA_B)), 0, 0, 0, 0, 0, 1, 0]); } public function rotateHue( degrees:Number ):void { initHue(); concat( preHue.matrix ); rotateBlue( degrees ); concat( postHue.matrix ); } public function luminance2Alpha():void { concat([0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, LUMA_R, LUMA_G, LUMA_B, 0, 0]); } public function adjustAlphaContrast(amount:Number):void { amount += 1; concat([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, amount, (128 * (1 - amount))]); } public function colorize(rgb:int, amount:Number=1):void { var r:Number; var g:Number; var b:Number; var inv_amount:Number; r = (((rgb >> 16) & 0xFF) / 0xFF); g = (((rgb >> 8) & 0xFF) / 0xFF); b = ((rgb & 0xFF) / 0xFF); inv_amount = (1 - amount); concat([(inv_amount + ((amount * r) * LUMA_R)), ((amount * r) * LUMA_G), ((amount * r) * LUMA_B), 0, 0, ((amount * g) * LUMA_R), (inv_amount + ((amount * g) * LUMA_G)), ((amount * g) * LUMA_B), 0, 0, ((amount * b) * LUMA_R), ((amount * b) * LUMA_G), (inv_amount + ((amount * b) * LUMA_B)), 0, 0, 0, 0, 0, 1, 0]); } public function setChannels( r:int = 1, g:int = 2, b:int = 4, a:int = 8):void { var rf:Number = (((r & 1) == 1) ? 1 : 0 ) + (((r & 2) == 2) ? 1 : 0) + (((r & 4) == 4) ? 1 : 0) + (((r & 8) == 8) ? 1 : 0); if (rf > 0){ rf = (1 / rf); }; var gf:Number = (((g & 1) == 1) ? 1 : 0 ) + (((g & 2) == 2) ? 1 : 0) + (((g & 4) == 4) ? 1 : 0) + (((g & 8) == 8) ? 1 : 0); if (gf > 0){ gf = (1 / gf); }; var bf:Number = (((b & 1) == 1) ? 1 : 0 ) + (((b & 2) == 2) ? 1 : 0) + (((b & 4) == 4) ? 1 : 0) + (((b & 8) == 8) ? 1 : 0); if (bf > 0){ bf = (1 / bf); }; var af:Number = (((a & 1) == 1) ? 1 : 0 ) + (((a & 2) == 2) ? 1 : 0) + (((a & 4) == 4) ? 1 : 0) + (((a & 8) == 8) ? 1 : 0); if (af > 0){ af = (1 / af); }; concat([(((r & 1) == 1)) ? rf : 0, (((r & 2) == 2)) ? rf : 0, (((r & 4) == 4)) ? rf : 0, (((r & 8) == 8)) ? rf : 0, 0, (((g & 1) == 1)) ? gf : 0, (((g & 2) == 2)) ? gf : 0, (((g & 4) == 4)) ? gf : 0, (((g & 8) == 8)) ? gf : 0, 0, (((b & 1) == 1)) ? bf : 0, (((b & 2) == 2)) ? bf : 0, (((b & 4) == 4)) ? bf : 0, (((b & 8) == 8)) ? bf : 0, 0, (((a & 1) == 1)) ? af : 0, (((a & 2) == 2)) ? af : 0, (((a & 4) == 4)) ? af : 0, (((a & 8) == 8)) ? af : 0, 0]); } public function blend(mat:ColorMatrix, amount:Number):void { var inv_amount:Number = (1 - amount); var i:int = 0; while (i < 20) { matrix[i] = ((inv_amount * matrix[i]) + (amount * mat.matrix[i])); i++; }; } public function extrapolate(mat:ColorMatrix, factor:Number ):void { var i:int = 0; while (i < 20) { matrix[i] += ( mat.matrix[i] - matrix[i]) * factor; i++; }; } public function average( r:Number=ONETHIRD, g:Number=ONETHIRD, b:Number=ONETHIRD):void { concat([r, g, b, 0, 0, r, g, b, 0, 0, r, g, b, 0, 0, 0, 0, 0, 1, 0]); } public function threshold(threshold:Number, factor:Number=256):void { concat([(LUMA_R * factor), (LUMA_G * factor), (LUMA_B * factor), 0, (-(factor-1) * threshold), (LUMA_R * factor), (LUMA_G * factor), (LUMA_B * factor), 0, (-(factor-1) * threshold), (LUMA_R * factor), (LUMA_G * factor), (LUMA_B * factor), 0, (-(factor-1) * threshold), 0, 0, 0, 1, 0]); } public function threshold_rgb(threshold:Number, factor:Number=256):void { concat([factor, 0, 0, 0, (-(factor-1) * threshold), 0, factor, 0, 0, (-(factor-1) * threshold), 0, 0, factor, 0, (-(factor-1) * threshold), 0, 0, 0, 1, 0]); } public function desaturate():void { concat([LUMA_R, LUMA_G, LUMA_B, 0, 0, LUMA_R, LUMA_G, LUMA_B, 0, 0, LUMA_R, LUMA_G, LUMA_B, 0, 0, 0, 0, 0, 1, 0]); } public function randomize(amount:Number=1):void { var inv_amount:Number = (1 - amount); var r1:Number = (inv_amount + (amount * (Math.random() - Math.random()))); var g1:Number = (amount * (Math.random() - Math.random())); var b1:Number = (amount * (Math.random() - Math.random())); var o1:Number = ((amount * 0xFF) * (Math.random() - Math.random())); var r2:Number = (amount * (Math.random() - Math.random())); var g2:Number = (inv_amount + (amount * (Math.random() - Math.random()))); var b2:Number = (amount * (Math.random() - Math.random())); var o2:Number = ((amount * 0xFF) * (Math.random() - Math.random())); var r3:Number = (amount * (Math.random() - Math.random())); var g3:Number = (amount * (Math.random() - Math.random())); var b3:Number = (inv_amount + (amount * (Math.random() - Math.random()))); var o3:Number = ((amount * 0xFF) * (Math.random() - Math.random())); concat([r1, g1, b1, 0, o1, r2, g2, b2, 0, o2, r3, g3, b3, 0, o3, 0, 0, 0, 1, 0]); } public function setMultiplicators( red:Number = 1, green:Number = 1, blue:Number = 1, alpha:Number = 1 ):void { var mat:Array = new Array ( red, 0, 0, 0, 0, 0, green, 0, 0, 0, 0, 0, blue, 0, 0, 0, 0, 0, alpha, 0 ); concat(mat); } public function clearChannels( red:Boolean = false, green:Boolean = false, blue:Boolean = false, alpha:Boolean = false ):void { if ( red ) { matrix[0] = matrix[1] = matrix[2] = matrix[3] = matrix[4] = 0; } if ( green ) { matrix[5] = matrix[6] = matrix[7] = matrix[8] = matrix[9] = 0; } if ( blue ) { matrix[10] = matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0; } if ( alpha ) { matrix[15] = matrix[16] = matrix[17] = matrix[18] = matrix[19] = 0; } } public function thresholdAlpha( threshold:Number, factor:Number = 256):void { concat([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, factor, (-factor * threshold)]); } public function averageRGB2Alpha():void { concat([0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, ONETHIRD, ONETHIRD, ONETHIRD, 0, 0]); } public function invertAlpha():void { concat([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 255]); } public function rgb2Alpha( r:Number, g:Number, b:Number ):void { concat([0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, r, g, b, 0, 0]); } public function setAlpha(alpha:Number):void { concat([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, alpha, 0]); } public function blue2Alpha( keepRGB:Boolean, foregroundColor:int = 0xffffff ):void { if ( keepRGB ) { matrix = [1,0,0,0,0, 0,1,0,0,0, 0,0,1,0,0, matrix[0],matrix[1],matrix[2],0,matrix[4]] } else { matrix = [0,0,0,0,(foregroundColor >> 16) & 0xff, 0,0,0,0,(foregroundColor >> 8) & 0xff, 0,0,0,0,foregroundColor & 0xff, matrix[0],matrix[1],matrix[2],0,matrix[4]]; } } public function get filter():ColorMatrixFilter { return new ColorMatrixFilter( matrix ); } public function applyFilter( bitmapData:BitmapData ):void { bitmapData.applyFilter( bitmapData, bitmapData.rect, new Point(), filter ); } public function concat( mat:Array ):void { var temp:Array = tempMatrix; var i:int = 0; var x:int, y:int; for (y = 0; y < 4; y++ ) { for (x = 0; x < 5; x++ ) { temp[ int( i + x) ] = mat[i ] * matrix[x] + mat[int(i+1)] * matrix[int(x + 5)] + mat[int(i+2)] * matrix[int(x + 10)] + mat[int(i+3)] * matrix[int(x + 15)] + (x == 4 ? mat[int(i+4)] : 0); } i+=5; } tempMatrix = matrix; matrix = temp; } public function rotateRed( degrees:Number ):void { rotateColor( degrees, 2, 1 ); } public function rotateGreen( degrees:Number ):void { rotateColor( degrees, 0, 2 ); } public function rotateBlue( degrees:Number ):void { rotateColor( degrees, 1, 0 ); } public function normalize():void { for ( var i:int = 0; i < 4; i++ ) { var sum:Number = 0; for ( var j:int = 0; j < 4; j++ ) { sum += matrix[i*5+j] * matrix[i*5+j]; } sum = 1 / Math.sqrt( sum ); if ( sum != 1 ) { for ( j = 0; j < 4; j++ ) { matrix[i*5+j] *= sum; } } } } public function fitRange():void { for ( var i:int = 0; i < 4; i++ ) { var minFactor:Number = 0; var maxFactor:Number = 0; for ( var j:int = 0; j < 4; j++ ) { if ( matrix[i*5+j] < 0 ) minFactor += matrix[i*5+j]; else maxFactor += matrix[i*5+j]; } var range:Number = maxFactor * 255 - minFactor * 255; var rangeCorrection:Number = 255 / range; if ( rangeCorrection != 1 ) { for ( j = 0; j < 4; j++ ) { matrix[i*5+j] *= rangeCorrection; } } minFactor = 0; maxFactor = 0; for ( j = 0; j < 4; j++ ) { if ( matrix[i*5+j] < 0 ) minFactor += matrix[i*5+j]; else maxFactor += matrix[i*5+j]; } var worstMin:Number = minFactor * 255; var worstMax:Number = maxFactor * 255; matrix[i*5+4] = - ( worstMin + ( worstMax - worstMin ) * 0.5 - 127.5 ); } } private function rotateColor( degrees:Number, x:int, y:int ):void { degrees *= RAD; var mat:Array = IDENTITY.concat(); mat[ x + x * 5 ] = mat[ y + y * 5 ] = Math.cos( degrees ); mat[ y + x * 5 ] = Math.sin( degrees ); mat[ x + y * 5 ] = -Math.sin( degrees ); concat( mat ); } public function shearRed( green:Number, blue:Number ):void { shearColor( 0, 1, green, 2, blue ); } public function shearGreen( red:Number, blue:Number ):void { shearColor( 1, 0, red, 2, blue ); } public function shearBlue( red:Number, green:Number ):void { shearColor( 2, 0, red, 1, green ); } private function shearColor( x:int, y1:int, d1:Number, y2:int, d2:Number ):void { var mat:Array = IDENTITY.concat(); mat[ y1 + x * 5 ] = d1; mat[ y2 + x * 5 ] = d2; concat( mat ); } public function scale( r:Number, g:Number = NaN, b:Number = NaN ):void { if (isNaN(g)) g = r; if (isNaN(b)) b = r; concat([r, 0, 0, 0, 0, 0, g, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]); } public function applyColorDeficiency( type:String ):void { // the values of this method are copied from http://www.nofunc.com/Color_Matrix_Library/ switch ( type ) { case 'Protanopia': concat([0.567,0.433,0,0,0, 0.558,0.442,0,0,0, 0,0.242,0.758,0,0, 0,0,0,1,0]); break; case 'Protanomaly': concat([0.817,0.183,0,0,0, 0.333,0.667,0,0,0, 0,0.125,0.875,0,0, 0,0,0,1,0]); break; case 'Deuteranopia': concat([0.625,0.375,0,0,0, 0.7,0.3,0,0,0, 0,0.3,0.7,0,0, 0,0,0,1,0]); break; case 'Deuteranomaly': concat([0.8,0.2,0,0,0, 0.258,0.742,0,0,0, 0,0.142,0.858,0,0, 0,0,0,1,0]); break; case 'Tritanopia': concat([0.95,0.05,0,0,0, 0,0.433,0.567,0,0, 0,0.475,0.525,0,0, 0,0,0,1,0]); break; case 'Tritanomaly': concat([0.967,0.033,0,0,0, 0,0.733,0.267,0,0, 0,0.183,0.817,0,0, 0,0,0,1,0]); break; case 'Achromatopsia': concat([0.299,0.587,0.114,0,0, 0.299,0.587,0.114,0,0, 0.299,0.587,0.114,0,0, 0,0,0,1,0]); break; case 'Achromatomaly': concat([0.618,0.320,0.062,0,0, 0.163,0.775,0.062,0,0, 0.163,0.320,0.516,0,0, 0,0,0,1,0]); break; } } public function RGB2YUV():void { concat([ 0.29900, 0.58700, 0.11400, 0, 0, -0.16874, -0.33126, 0.50000, 0, 128, 0.50000, -0.41869, -0.08131, 0, 128, 0 , 0 , 0 , 1, 0 ]); } public function YUV2RGB():void { concat([ 1 , -0.000007154783816076815, 1.4019975662231445 , 0, -179.45477266423404, 1 , -0.3441331386566162 , -0.7141380310058594 , 0, 135.45870971679688, 1 , 1.7720025777816772 , 0.00001542569043522235, 0, -226.8183044444304, 0 , 0 , 0 , 1, 0 ]); } public function RGB2YIQ():void { concat([ 0.2990, 0.5870, 0.1140, 0, 0, 0.595716, -0.274453, -0.321263, 0, 128, 0.211456, -0.522591, -0.311135, 0, 128, 0 , 0 , 0 , 1, 0 ]); } /* public function YIQ2RGB():void { concat([ 1, ,-0.000007154783816076815, 1.4019975662231445 , 0, -179.45477266423404, 1 , -0.3441331386566162 , -0.7141380310058594 , 0, 135.45870971679688, 1 , 1.7720025777816772 , 0.00001542569043522235, 0, -226.8183044444304, 0 , 0 , 0 , 1, 0 ]); } */ public function autoDesaturate( bitmapData:BitmapData, stretchLevels:Boolean = false, outputToBlueOnly:Boolean = false, tolerance:Number = 0.01 ):void { var histogram:Vector.> = bitmapData.histogram(bitmapData.rect ); var sum_r:Number = 0; var sum_g:Number = 0; var sum_b:Number = 0; var min:Number; var max:Number; var minFound:Boolean = false; var histR:Vector. = histogram[0]; var histG:Vector. = histogram[1]; var histB:Vector. = histogram[2]; for ( var i:int = 0; i < 256; i++ ) { sum_r += histR[i] * i; sum_g += histG[i] * i; sum_b += histB[i] * i; } var total:Number = sum_r + sum_g + sum_b; if ( total == 0 ) { total = 3; sum_r = sum_g = sum_b = 3; } sum_r /= total; sum_g /= total; sum_b /= total; var offset:Number = 0; if ( stretchLevels ) { var minPixels:Number = bitmapData.rect.width * bitmapData.rect.height * tolerance; var sr:Number = 0; var sg:Number = 0; var sb:Number = 0; for ( i = 0; i < 256; i++ ) { sr += histR[i]; sg += histG[i]; sb += histB[i]; if ( sr > minPixels || sg > minPixels || sb > minPixels ) { min = i; break; } } sr = 0; sg = 0; sb = 0; for ( i = 256; --i > -1; ) { sr += histR[i]; sg += histG[i]; sb += histB[i]; if ( sr > minPixels || sg > minPixels || sb > minPixels ) { max = i; break; } } if ( max - min < 255) { var f:Number = 256 / ((max - min) + 1); sum_r *= f; sum_g *= f; sum_b *= f; offset = -min; } } f = 1 / Math.sqrt(sum_r * sum_r + sum_g * sum_g + sum_b * sum_b); sum_r *= f; sum_g *= f; sum_b *= f; if ( !outputToBlueOnly ) concat([sum_r,sum_g,sum_b,0,offset, sum_r,sum_g,sum_b,0,offset, sum_r,sum_g,sum_b,0,offset, 0,0,0,1,0]); else concat([0,0,0,0,0, 0,0,0,0,0, sum_r,sum_g,sum_b,0,offset, 0,0,0,1,0]); } public function applyMatrix3D( matrix:Matrix3D ):void { /* concat([matrix.rawData[0],matrix.rawData[1],matrix.rawData[2],matrix.rawData[3],matrix.rawData[12], matrix.rawData[4],matrix.rawData[5],matrix.rawData[6],matrix.rawData[7],matrix.rawData[13], matrix.rawData[8],matrix.rawData[9],matrix.rawData[10],matrix.rawData[11],matrix.rawData[14], 0,0,0,matrix.rawData[15],0]); */ concat([matrix.rawData[0],matrix.rawData[4],matrix.rawData[8],0,matrix.rawData[12], matrix.rawData[1],matrix.rawData[5],matrix.rawData[9],0,matrix.rawData[13], matrix.rawData[2],matrix.rawData[6],matrix.rawData[10],0,matrix.rawData[14], matrix.rawData[3],matrix.rawData[7],matrix.rawData[11],matrix.rawData[15],0]); } public function setMatrix3D( matrix:Matrix3D ):void { this.matrix = [matrix.rawData[0],matrix.rawData[4],matrix.rawData[8],0,matrix.rawData[12], matrix.rawData[1],matrix.rawData[5],matrix.rawData[9],0,matrix.rawData[13], matrix.rawData[2],matrix.rawData[6],matrix.rawData[10],0,matrix.rawData[14], 0,0,0,matrix.rawData[15],0]; /* concat([matrix.rawData[0],matrix.rawData[4],matrix.rawData[8],0,matrix.rawData[12], matrix.rawData[1],matrix.rawData[5],matrix.rawData[9],0,matrix.rawData[13], matrix.rawData[2],matrix.rawData[5],matrix.rawData[10],0,matrix.rawData[14], matrix.rawData[3],matrix.rawData[7],matrix.rawData[11],matrix.rawData[15],0]); */ } public function invertMatrix():Boolean { var coeffs:Matrix3D = new Matrix3D( Vector.( [matrix[0],matrix[1],matrix[2],matrix[3], matrix[5],matrix[6],matrix[7],matrix[8], matrix[10],matrix[11],matrix[12],matrix[13], matrix[15],matrix[16],matrix[17],matrix[18]] ) ); var check:Boolean = coeffs.invert(); if (!check) return false; matrix[0] = coeffs.rawData[0]; matrix[1] = coeffs.rawData[1]; matrix[2] = coeffs.rawData[2]; matrix[3] = coeffs.rawData[3]; var tmp1:Number = -( coeffs.rawData[0] * matrix[4] + coeffs.rawData[1] * matrix[9] + coeffs.rawData[2] * matrix[14] + coeffs.rawData[3] * matrix[15] ); matrix[5] = coeffs.rawData[4]; matrix[6] = coeffs.rawData[5]; matrix[7] = coeffs.rawData[6]; matrix[8] = coeffs.rawData[7]; var tmp2:Number = -( coeffs.rawData[4] * matrix[4] + coeffs.rawData[5] * matrix[9] + coeffs.rawData[6] * matrix[14] + coeffs.rawData[7] * matrix[15] ); matrix[10] = coeffs.rawData[8]; matrix[11] = coeffs.rawData[9]; matrix[12] = coeffs.rawData[10]; matrix[13] = coeffs.rawData[11]; var tmp3:Number = -( coeffs.rawData[8] * matrix[4] + coeffs.rawData[9] * matrix[9] + coeffs.rawData[10] * matrix[14] + coeffs.rawData[11] * matrix[15] ); matrix[15] = coeffs.rawData[12]; matrix[16] = coeffs.rawData[13]; matrix[17] = coeffs.rawData[14]; matrix[18] = coeffs.rawData[15]; var tmp4:Number = -( coeffs.rawData[12] * matrix[4] + coeffs.rawData[13] * matrix[9] + coeffs.rawData[14] * matrix[14] + coeffs.rawData[15] * matrix[15] ); matrix[4] = tmp1; matrix[9] = tmp2; matrix[14] = tmp3; matrix[19] = tmp4; return true; } public function applyMatrix( rgba:uint ):uint { var a:Number = ( rgba >>> 24 ) & 0xff; var r:Number = ( rgba >>> 16 ) & 0xff; var g:Number = ( rgba >>> 8 ) & 0xff; var b:Number = rgba & 0xff; var r2:int = 0.5 + r * matrix[0] + g * matrix[1] + b * matrix[2] + a * matrix[3] + matrix[4]; var g2:int = 0.5 + r * matrix[5] + g * matrix[6] + b * matrix[7] + a * matrix[8] + matrix[9]; var b2:int = 0.5 + r * matrix[10] + g * matrix[11] + b * matrix[12] + a * matrix[13] + matrix[14]; var a2:int = 0.5 + r * matrix[15] + g * matrix[16] + b * matrix[17] + a * matrix[18] + matrix[19]; if ( a2 < 0 ) a2 = 0; if ( a2 > 255 ) a2 = 255; if ( r2 < 0 ) r2 = 0; if ( r2 > 255 ) r2 = 255; if ( g2 < 0 ) g2 = 0; if ( g2 > 255 ) g2 = 255; if ( b2 < 0 ) b2 = 0; if ( b2 > 255 ) b2 = 255; return a2<<24 | r2<<16 | g2<<8 | b2; } // this assumes a vector containing a series of 4 floating point colors 0...1 // this is used in psykopaint public function applyMatrixToVector( rgba:Vector. ):void { var i255:Number = 1 / 255; var roffset:Number = matrix[4] * i255; var goffset:Number = matrix[9] * i255; var boffset:Number = matrix[14] * i255; var aoffset:Number = matrix[19] * i255; for ( var i:int = 0; i < 4; i++ ) { var r:Number = rgba[i<<2]; var g:Number = rgba[(i<<2)+1]; var b:Number = rgba[(i<<2)+2]; var a:Number = rgba[(i<<2)+3]; var r2:Number = r * matrix[0] + g * matrix[1] + b * matrix[2] + a * matrix[3] + roffset; var g2:Number = r * matrix[5] + g * matrix[6] + b * matrix[7] + a * matrix[8] + goffset; var b2:Number = r * matrix[10] + g * matrix[11] + b * matrix[12] + a * matrix[13] + boffset; var a2:Number = r * matrix[15] + g * matrix[16] + b * matrix[17] + a * matrix[18] + aoffset; if ( a2 < 0 ) a2 = 0; else if ( a2 > 1 ) a2 = 1; if ( r2 < 0 ) r2 = 0; else if ( r2 > 1 ) r2 = 1; if ( g2 < 0 ) g2 = 0; else if ( g2 > 1 ) g2 = 1; if ( b2 < 0 ) b2 = 0; else if ( b2 > 1 ) b2 = 1; rgba[i<<2] = r2; rgba[(i<<2)+1] = g2; rgba[(i<<2)+2] = b2; rgba[(i<<2)+3] = a2; } } public function transformVector( values:Array ):void { if ( values.length != 4) return; var r:Number = values[0] * matrix[0] + values[1] * matrix[1] + values[2] * matrix[2] + values[3] * matrix[3] + matrix[4]; var g:Number = values[0] * matrix[5] + values[1] * matrix[6] + values[2] * matrix[7] + values[3] * matrix[8] + matrix[9]; var b:Number = values[0] * matrix[10] + values[1] * matrix[11] + values[2] * matrix[12] + values[3] * matrix[13] + matrix[14]; var a:Number = values[0] * matrix[15] + values[1] * matrix[16] + values[2] * matrix[17] + values[3] * matrix[18] + matrix[19]; values[0] = r; values[1] = g; values[2] = b; values[3] = a; } private function initHue():void { //var greenRotation:Number = 35.0; var greenRotation:Number = 39.182655; if (!hueInitialized) { hueInitialized = true; preHue = new ColorMatrix(); preHue.rotateRed( 45 ); preHue.rotateGreen(- greenRotation ); var lum:Array = [ LUMA_R2, LUMA_G2, LUMA_B2, 1.0 ]; preHue.transformVector(lum); var red:Number = lum[0] / lum[2]; var green:Number = lum[1] / lum[2]; preHue.shearBlue(red, green); postHue = new ColorMatrix(); postHue.shearBlue( -red, -green); postHue.rotateGreen(greenRotation); postHue.rotateRed(- 45.0 ); } } public function toAGALVector():Vector. { return Vector.( [ matrix[0],matrix[1],matrix[2],matrix[3], matrix[5],matrix[6],matrix[7],matrix[8], matrix[10],matrix[11],matrix[12],matrix[13], matrix[15],matrix[16],matrix[17],matrix[18], matrix[4] / 255,matrix[9] / 255,matrix[14] / 255,matrix[19] / 255 ]); } public function toString():String { return matrix.toString(); } } }",12100,False,2213.8017829044657,median "CLASS zcl_adf_service DEFINITION PUBLIC ABSTRACT CREATE PUBLIC. PUBLIC SECTION. METHODS send IMPORTING VALUE(request) TYPE xstring !it_headers TYPE tihttpnvp OPTIONAL EXPORTING VALUE(response) TYPE string VALUE(ev_http_status) TYPE i RAISING zcx_adf_service . METHODS constructor IMPORTING VALUE(iv_interface_id) TYPE zinterface_id VALUE(iv_service_id) TYPE zazure_dest VALUE(iv_business_identifier) TYPE zbusinessid OPTIONAL RAISING zcx_adf_service zcx_http_client_failed zcx_interace_config_missing . METHODS format_data IMPORTING VALUE(iv_format_type) TYPE zadf_format_type VALUE(it_data) TYPE data RETURNING VALUE(rv_string) TYPE string RAISING zcx_adf_service . METHODS format_data_to_xml IMPORTING VALUE(it_data) TYPE data RETURNING VALUE(rv_string) TYPE string . METHODS format_data_to_json IMPORTING VALUE(it_data) TYPE data RETURNING VALUE(rv_string) TYPE string . METHODS add_expiry_time IMPORTING VALUE(iv_expiry_hour) TYPE i VALUE(iv_expiry_min) TYPE i DEFAULT 30 VALUE(iv_expiry_sec) TYPE i RAISING zcx_adf_service . METHODS urlencoded_to_http_fields IMPORTING !iv_response_data TYPE string RETURNING VALUE(et_fields) TYPE tihttpnvp RAISING zcx_adf_service . METHODS json_to_http_fields IMPORTING !iv_response_data TYPE string RETURNING VALUE(et_fields) TYPE tihttpnvp RAISING zcx_adf_service . METHODS get_message_id RETURNING VALUE(rv_message_id) TYPE guid_16 . PROTECTED SECTION. CONSTANTS gc_error TYPE char1 VALUE 'E' ##NO_TEXT. DATA gv_interface_id TYPE zinterface_id . DATA gv_sas_key TYPE string . DATA gv_uri TYPE string . DATA go_rest_api TYPE REF TO zcl_rest_framework . TYPE-POOLS abap . DATA gv_asynchronous TYPE abap_bool . DATA gv_is_try TYPE abap_bool . DATA gv_expiry_hour TYPE i . DATA gv_expiry_min TYPE i . DATA gv_expiry_sec TYPE i . DATA gv_string_to_sign TYPE string . DATA gv_service_version TYPE string . DATA gv_rfc_destination TYPE rfcdest . DATA gv_path_prefix TYPE string . DATA gv_host TYPE string . DATA gt_headers TYPE tihttpnvp . METHODS add_request_header IMPORTING VALUE(iv_name) TYPE string VALUE(iv_value) TYPE string . METHODS get_sas_token IMPORTING VALUE(iv_baseaddress) TYPE string RETURNING VALUE(rv_sas_token) TYPE string RAISING zcx_adf_service . METHODS get_epoch_time RETURNING VALUE(rv_expiry_time) TYPE string RAISING zcx_adf_service . METHODS decode_sign RETURNING VALUE(rv_secret) TYPE string RAISING zcx_adf_service . METHODS get_target_host IMPORTING !iv_destination TYPE rfcdes-rfcdest !iv_authority_check TYPE rfcdisplay-rfctrace OPTIONAL !iv_bypass_buff TYPE char1 OPTIONAL EXPORTING !ev_server TYPE rfcdisplay-rfchost !ev_path_prefix TYPE string RAISING zcx_adf_service . PRIVATE SECTION. CONSTANTS gc_format_xml TYPE zadf_format_type VALUE 'XML' ##NO_TEXT. CONSTANTS gc_format_json TYPE zadf_format_type VALUE 'JSON' ##NO_TEXT. CONSTANTS gc_asynchronous TYPE char1 VALUE 'A' ##NO_TEXT. CONSTANTS gc_synchronous TYPE char1 VALUE 'S' ##NO_TEXT. DATA gv_destination TYPE zazure_dest . DATA gv_service_id TYPE zazure_dest . METHODS get_interface_details RAISING zcx_adf_service . METHODS get_rest_api_ref IMPORTING !iv_business_identifier TYPE zbusinessid OPTIONAL RAISING zcx_adf_service zcx_http_client_failed zcx_interace_config_missing . ENDCLASS. CLASS zcl_adf_service IMPLEMENTATION. METHOD add_expiry_time. CLEAR: gv_expiry_hour,gv_expiry_min,gv_expiry_sec. gv_expiry_hour = iv_expiry_hour. gv_expiry_min = iv_expiry_min. gv_expiry_sec = iv_expiry_sec. IF ( gv_expiry_hour IS INITIAL ) AND ( gv_expiry_min IS INITIAL ) AND ( gv_expiry_sec IS INITIAL ). RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>expiry_time_not_set interface_id = gv_interface_id. ENDIF. ENDMETHOD. METHOD add_request_header. go_rest_api->zif_rest_framework~set_request_header( iv_name = iv_name iv_value = iv_value ). ENDMETHOD. METHOD constructor. gv_interface_id = iv_interface_id. gv_service_id = iv_service_id. get_interface_details( ). get_rest_api_ref( iv_business_identifier = iv_business_identifier ). ENDMETHOD. METHOD decode_sign. *This Include is to encrypt secrets with SSL client ID from STRUST * *Framework Author : Krishna Chandra Dash * * Sasidhar Puranam * *----------------------------------------------------------------------* DATA : lv_rfc_destination TYPE zrest_config-destination, lv_srtfd TYPE zadf_con_indx-srtfd, lw_indx TYPE zadf_con_indx, lt_enveloped_data TYPE TABLE OF ssfbin, lv_cert_string TYPE xstring, lt_recipients TYPE TABLE OF ssfinfo, lw_recipient TYPE ssfinfo, lt_input_data TYPE TABLE OF ssfbin, lw_input_data TYPE ssfbin, lv_env_data_len TYPE i, lv_env_len_total TYPE i, lv_subject TYPE string, lw_enveloped_data TYPE ssfbin, lv_xstr_input TYPE xstring, lv_len_output TYPE i, lv_len_input TYPE i, lt_decoded_bin TYPE TABLE OF x, lv_decoded_str TYPE string, lv_applic TYPE rfcdisplay-sslapplic, lv_psename TYPE ssfpsename, lv_profilename TYPE localfile, lv_profile TYPE ssfparms-pab, ssl_active TYPE rfcsnc. lv_srtfd = gv_interface_id. DEFINE decode_key. *Import internal table as a cluster from INDX IMPORT tab = lt_enveloped_data[] FROM DATABASE zadf_con_indx(zd) TO lw_indx ID lv_srtfd. IF NOT lt_enveloped_data[] IS INITIAL. CLEAR lv_rfc_destination. SELECT SINGLE destination FROM zrest_config INTO lv_rfc_destination WHERE interface_id EQ gv_interface_id. IF NOT lv_rfc_destination IS INITIAL . CALL FUNCTION 'RFC_READ_HTTP_DESTINATION' EXPORTING destination = lv_rfc_destination authority_check = ' ' IMPORTING sslapplic = lv_applic ssl = ssl_active EXCEPTIONS authority_not_available = 1 destination_not_exist = 2 information_failure = 3 internal_failure = 4 no_http_destination = 5 OTHERS = 6. IF sy-subrc NE 0. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>read_error_rfc_destination interface_id = gv_interface_id. ENDIF. if ssl_active <> abap_true. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>RFC_DESTINATION_NO_SSL rfc_destination = lv_rfc_destination interface_id = gv_interface_id. endif. CALL FUNCTION 'SSFPSE_FILENAME' EXPORTING mandt = sy-mandt context = 'SSLC' applic = lv_applic IMPORTING psename = lv_psename profile = lv_profilename EXCEPTIONS pse_not_found = 1 OTHERS = 2. IF sy-subrc NE 0. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>read_error_pse_filename interface_id = gv_interface_id. ENDIF. IF NOT lv_psename IS INITIAL. lv_profile = lv_psename. CALL FUNCTION 'SSFC_GET_CERTIFICATE' EXPORTING profile = lv_profile IMPORTING certificate = lv_cert_string EXCEPTIONS ssf_krn_error = 1 ssf_krn_nomemory = 2 ssf_krn_nossflib = 3 ssf_krn_invalid_par = 4 ssf_krn_nocertificate = 5 OTHERS = 6. IF sy-subrc NE 0. **Addinng complete profile path for reading certificate instance lv_profile = lv_profilename. CALL FUNCTION 'SSFC_GET_CERTIFICATE' EXPORTING profile = lv_profile IMPORTING certificate = lv_cert_string EXCEPTIONS ssf_krn_error = 1 ssf_krn_nomemory = 2 ssf_krn_nossflib = 3 ssf_krn_invalid_par = 4 ssf_krn_nocertificate = 5 OTHERS = 6. IF sy-subrc NE 0. **Raise Exception RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>error_get_certificate_instance interface_id = gv_interface_id. ENDIF. ENDIF. CALL FUNCTION 'SSFC_PARSE_CERTIFICATE' EXPORTING certificate = lv_cert_string IMPORTING subject = lv_subject EXCEPTIONS ssf_krn_error = 1 ssf_krn_nomemory = 2 ssf_krn_nossflib = 3 ssf_krn_invalid_par = 4 OTHERS = 5. IF sy-subrc NE 0. **Raise Exception RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>error_attributes_certificate interface_id = gv_interface_id. ENDIF. lw_recipient-id = lv_subject. lw_recipient-profile = lv_profile. APPEND lw_recipient TO lt_recipients. LOOP AT lt_enveloped_data INTO lw_enveloped_data. lv_env_data_len = xstrlen( lw_enveloped_data-bindata ). lv_env_len_total = lv_env_len_total + lv_env_data_len. CLEAR lw_enveloped_data. ENDLOOP. CALL FUNCTION 'SSF_KRN_DEVELOPE' EXPORTING ssftoolkit = 'SAPSECULIB' str_format = 'PKCS7' * B_OUTDEC = 'X' * IO_SPEC = 'T' ostr_enveloped_data_l = lv_env_len_total IMPORTING ostr_output_data_l = lv_len_input * CRC = TABLES ostr_enveloped_data = lt_enveloped_data recipient = lt_recipients ostr_output_data = lt_input_data EXCEPTIONS ssf_krn_error = 1 ssf_krn_noop = 2 ssf_krn_nomemory = 3 ssf_krn_opinv = 4 ssf_krn_nossflib = 5 ssf_krn_recipient_error = 6 ssf_krn_input_data_error = 7 ssf_krn_invalid_par = 8 ssf_krn_invalid_parlen = 9 ssf_fb_input_parameter_error = 10 OTHERS = 11. IF sy-subrc NE 0. **Raise Exception RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>error_decode_sas_key interface_id = gv_interface_id. ENDIF. IF NOT lt_input_data[] IS INITIAL. CALL FUNCTION 'SCMS_BINARY_TO_STRING' EXPORTING input_length = lv_len_input IMPORTING text_buffer = lv_decoded_str output_length = lv_len_output TABLES binary_tab = lt_input_data EXCEPTIONS failed = 1 OTHERS = 2. IF lv_decoded_str IS INITIAL. **Raise exception RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>error_con_saskey_string interface_id = gv_interface_id. ELSE. rv_secret = lv_decoded_str. ENDIF. ELSE. **Raise exception RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>error_read_encoded_saskey interface_id = gv_interface_id. ENDIF. ENDIF. ELSE. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>rfc_destination_not_maintained interface_id = gv_interface_id. ENDIF. ELSE. **Raise Exception RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>error_import_sas_key interface_id = gv_interface_id. ENDIF. IF rv_secret IS INITIAL. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>sas_key_not_maintained interface_id = gv_interface_id. ENDIF. END-OF-DEFINITION. decode_key. ENDMETHOD. METHOD format_data. CASE iv_format_type. WHEN gc_format_xml. rv_string = format_data_to_xml( it_data ). WHEN gc_format_json. rv_string = format_data_to_json( it_data ). WHEN OTHERS. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>format_not_supported format_type = iv_format_type. ENDCASE. ENDMETHOD. METHOD format_data_to_json. DATA : lo_json TYPE REF TO cl_trex_json_serializer. CREATE OBJECT lo_json EXPORTING data = it_data. lo_json->serialize( ). rv_string = lo_json->get_data( ). ENDMETHOD. METHOD format_data_to_xml. CALL TRANSFORMATION ('ID') SOURCE itab = it_data RESULT XML rv_string. ENDMETHOD. METHOD get_epoch_time. DATA : lv_start_timestamp TYPE timestampl, lv_current_timestamp TYPE timestampl, lv_seconds TYPE p, lv_input_seconds TYPE p, zcx_adf_service TYPE REF TO zcx_adf_service. DATA: date TYPE datum, time TYPE uzeit. *Get the current timestamp GET TIME STAMP FIELD lv_current_timestamp . *Get the time difference DATA zone TYPE sy-zonlo. CONVERT TIME STAMP lv_current_timestamp TIME ZONE zone INTO DATE date TIME time. TRY. CALL METHOD cl_abap_tstmp=>td_subtract EXPORTING date1 = date time1 = time date2 = '19700101' time2 = '000000' IMPORTING res_secs = lv_seconds. * Add expiry time in seconds lv_input_seconds = ( ( gv_expiry_hour * 60 ) * 60 ) + ( gv_expiry_min * 60 ) + ( gv_expiry_sec ). lv_seconds = lv_seconds + lv_input_seconds. rv_expiry_time = lv_seconds. CONDENSE rv_expiry_time. CATCH cx_parameter_invalid_type. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>parameter_invalid_type interface_id = gv_interface_id. CATCH cx_parameter_invalid_range . RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>parameter_invalid_range interface_id = gv_interface_id. ENDTRY. ENDMETHOD. METHOD get_interface_details. DATA : ls_config TYPE zadf_config, lv_host TYPE rfcdisplay-rfchost, lv_host_s TYPE string, lv_path_prefix TYPE string. SELECT SINGLE * FROM zadf_config INTO ls_config WHERE interface_id = gv_interface_id. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>interface_not_available interface_id = gv_interface_id. ENDIF. SELECT SINGLE destination FROM zrest_config INTO gv_rfc_destination WHERE interface_id = gv_interface_id. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>interface_not_available interface_id = gv_interface_id. ENDIF. **Getting Target host of RFC destination get_target_host( EXPORTING iv_destination = gv_rfc_destination IMPORTING ev_server = lv_host ev_path_prefix = lv_path_prefix ). gv_host = lv_host. gv_path_prefix = lv_path_prefix. lv_host_s = lv_host. CONCATENATE lv_host_s lv_path_prefix INTO gv_uri. IF gv_uri IS INITIAL. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>uri_not_maintained interface_id = gv_interface_id. ENDIF. IF ls_config-service_type IS INITIAL. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>call_type_not_maintained interface_id = gv_interface_id. ELSEIF ls_config-service_type EQ gc_synchronous. gv_asynchronous = abap_false. ELSEIF ls_config-service_type EQ gc_asynchronous. gv_asynchronous = abap_true. ENDIF. gv_is_try = ls_config-is_try. gv_sas_key = ls_config-sas_key. ""Added by KRDASH ENDMETHOD. METHOD get_message_id. rv_message_id = go_rest_api->get_guid( ). ENDMETHOD. METHOD get_rest_api_ref. DATA : lcx_interface TYPE REF TO zcx_interace_config_missing, lcx_http TYPE REF TO zcx_http_client_failed, lv_method TYPE char20. IF go_rest_api IS INITIAL. CLEAR lv_method. SELECT SINGLE method FROM zrest_conf_misc INTO lv_method WHERE interface_id EQ gv_interface_id. IF lv_method IS INITIAL. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>method_not_maintained interface_id = gv_interface_id. ENDIF. TRY. CREATE OBJECT go_rest_api EXPORTING interface_name = gv_interface_id ""Mandatory business_identifier = iv_business_identifier method = lv_method. ""For troubleshooting CATCH zcx_interace_config_missing INTO lcx_interface. RAISE EXCEPTION lcx_interface. CATCH zcx_http_client_failed INTO lcx_http . RAISE EXCEPTION lcx_http. ENDTRY. IF go_rest_api IS BOUND. *Optional - To help developer understand the origin of call go_rest_api->set_callingmethod( zimethodname = 'SEND' ). *Optional - To help developer understand the origin of call go_rest_api->set_callingprogram( ziclassname = 'ZCL_ADF_SERVICE' ). ELSE. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>error_rest_api_instance interface_id = gv_interface_id. ENDIF. ENDIF. ENDMETHOD. METHOD get_sas_token. DATA : lv_string_to_sign TYPE string, encoded_base_address TYPE string, body_xstring TYPE xstring, sign TYPE string, final_token TYPE string, decoded TYPE xstring, conv TYPE REF TO cl_abap_conv_out_ce, conv_in TYPE REF TO cl_abap_conv_in_ce, format TYPE i, new_expiry TYPE string, lv_sas_key TYPE string, lv_expiry_time TYPE string. get_epoch_time( RECEIVING rv_expiry_time = lv_expiry_time ). format = 18. encoded_base_address = escape( val = iv_baseaddress format = format ). CONCATENATE encoded_base_address cl_abap_char_utilities=>newline lv_expiry_time INTO lv_string_to_sign. conv = cl_abap_conv_out_ce=>create( encoding = 'UTF-8' ). conv->convert( EXPORTING data = lv_string_to_sign IMPORTING buffer = body_xstring ). DEFINE encrypt_key. decode_sign( RECEIVING rv_secret = lv_sas_key ). conv = cl_abap_conv_out_ce=>create( encoding = 'UTF-8' ). conv->convert( EXPORTING data = lv_sas_key IMPORTING buffer = decoded ). CALL METHOD cl_abap_hmac=>calculate_hmac_for_raw EXPORTING if_algorithm = 'sha-256' if_key = decoded if_data = body_xstring if_length = 0 IMPORTING ef_hmacb64string = sign. CLEAR : lv_sas_key, decoded. END-OF-DEFINITION. encrypt_key. new_expiry = lv_expiry_time. CONDENSE new_expiry. IF NOT sign IS INITIAL. sign = escape( val = sign format = format ). CONCATENATE 'SharedAccessSignature sr=' encoded_base_address '&sig=' sign '&se=' new_expiry '&skn=' 'edit' INTO final_token. rv_sas_token = final_token. ELSE. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>sas_key_not_generated interface_id = gv_interface_id. ENDIF. ENDMETHOD. METHOD get_target_host. DATA: ssl_active TYPE rfcsnc. CALL FUNCTION 'RFC_READ_HTTP_DESTINATION' EXPORTING destination = iv_destination authority_check = iv_authority_check bypass_buf = iv_bypass_buff IMPORTING server = ev_server path_prefix = ev_path_prefix ssl = ssl_active EXCEPTIONS authority_not_available = 1 destination_not_exist = 2 information_failure = 3 internal_failure = 4 no_http_destination = 5 OTHERS = 6. IF sy-subrc <> 0. * Implement suitable error handling here RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>read_error_rfc_destination interface_id = gv_interface_id. ENDIF. IF ssl_active <> abap_true. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>rfc_destination_no_ssl rfc_destination = iv_destination interface_id = gv_interface_id. ENDIF. ENDMETHOD. METHOD json_to_http_fields. DATA: ls_fields TYPE ihttpnvp, l_node TYPE REF TO if_sxml_node, l_error TYPE string, lr_open_element TYPE REF TO if_sxml_open_element, lt_attributes TYPE if_sxml_attribute=>attributes, ls_attribute LIKE LINE OF lt_attributes, lr_value_node TYPE REF TO if_sxml_value_node, json TYPE xstring, reader TYPE REF TO if_sxml_reader, parse_error TYPE REF TO cx_sxml_parse_error. TRY . json = cl_abap_codepage=>convert_to( iv_response_data ). reader = cl_sxml_string_reader=>create( json ). "" after parse, the json response should look like following DO. CLEAR ls_fields. l_node = reader->read_next_node( ). IF l_node IS INITIAL. EXIT. ENDIF. CASE l_node->type. WHEN if_sxml_node=>co_nt_element_open. lr_open_element ?= l_node. lt_attributes = lr_open_element->get_attributes( ). IF lt_attributes IS NOT INITIAL. "" get name READ TABLE lt_attributes INDEX 1 INTO ls_attribute. ls_fields-name = ls_attribute->get_value( ). "" get value l_node = reader->read_next_node( ). IF l_node->type = if_sxml_node=>co_nt_value. lr_value_node ?= l_node . ls_fields-value = lr_value_node->get_value( ). "" add field into the result table APPEND ls_fields TO et_fields. ENDIF. ENDIF. WHEN OTHERS. "" do nothing ENDCASE. ENDDO. CATCH cx_sxml_parse_error INTO parse_error. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>parse_error interface_id = gv_interface_id. ENDTRY. ENDMETHOD. METHOD send. DATA : lo_response TYPE REF TO if_rest_entity, lo_request TYPE REF TO if_rest_entity, lv_expiry TYPE string, lv_sas_token TYPE string, lv_msg TYPE string, lcx_adf_service TYPE REF TO zcx_adf_service. IF go_rest_api IS BOUND. TRY. get_sas_token( EXPORTING iv_baseaddress = gv_uri RECEIVING rv_sas_token = lv_sas_token ). CATCH zcx_adf_service INTO lcx_adf_service. lv_msg = lcx_adf_service->get_text( ). MESSAGE lv_msg TYPE 'I'. ENDTRY. add_request_header( iv_name = 'Content-Type' iv_value = 'application/json; charset=utf-8' ). add_request_header( iv_name = 'Authorization' iv_value = lv_sas_token ). go_rest_api->zif_rest_framework~set_binary_body( request ). IF NOT it_headers[] IS INITIAL. go_rest_api->zif_rest_framework~set_request_headers( it_header_fields = it_headers[] ). ENDIF. **Rest API call to get response from Azure Destination lo_response = go_rest_api->zif_rest_framework~execute( io_entity = lo_request async = gv_asynchronous is_retry = gv_is_try ). ev_http_status = go_rest_api->get_status( ). go_rest_api->close( ). IF lo_response IS BOUND. response = lo_response->get_string_data( ). ELSE. RAISE EXCEPTION TYPE zcx_adf_service EXPORTING textid = zcx_adf_service=>restapi_response_not_found interface_id = gv_interface_id. ENDIF. ENDIF. ENDMETHOD. METHOD urlencoded_to_http_fields. DATA: lt_params TYPE STANDARD TABLE OF string, ls_response_field LIKE LINE OF et_fields. FIELD-SYMBOLS: LIKE LINE OF lt_params. SPLIT iv_response_data AT `&` INTO TABLE lt_params. LOOP AT lt_params ASSIGNING . SPLIT AT `=` INTO ls_response_field-name ls_response_field-value. APPEND ls_response_field TO et_fields. ENDLOOP. ENDMETHOD. ENDCLASS. ",6296,False,1324.5417921634232,median ";**********************************************************************; ; ; ; This file is part of ZSM4, a Z80/Z180/Z280 relocatable macro- ; ; assembler written in Z80 assembly. ; ; Copyright (C) 2017-2020, Hector Peraza. ; ; Modified by Ladislau Szilagyi ( dec 2021 - jan 2022 ) ; ; ; ; This program is free software; you can redistribute it and/or ; ; modify it under the terms of the GNU General Public License as ; ; published by the Free Software Foundation; either version 2 of ; ; the License, or (at your option) any later version. ; ; ; ; This program is distributed in the hope that it will be useful, ; ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; ; GNU General Public License for more details. ; ; ; ; You should have received a copy of the GNU General Public License ; ; along with this program; if not, write to the Free Software ; ; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ; ; ; ;**********************************************************************; *include ZSM.INC GLOBAL ID,ADDSYM ; Macro types $MACRO equ 1 $REPT equ 2 $IRP equ 3 $IRPC equ 4 ;public global DEFMAC,ENDMAC,MSTORE,MDFLVL,MACLVL,DFREPT global DFIRP,DFIRPC,GNRMAC,FNDMAC,EXPMAC,GETSTR global MACPTR,CVTNUM,LCLNUM ;extern global ID,REC,SYMPTR,NEWSYM,DSPTR,IDADR,IDBUF,IDLEN global GNC,ERRFLG,PTR1,FNDOPC,EVALNEW,RELERR,OERROR global VALID,BACKUP,EVMODE,WERROR,FNDREC,FNDNXT,MFREE global CNV2HX,MCHECK,MACCHK,ERRQ,GNR,RADIX,SYMLUK global SYMTBL,GBCOL,CNDSTK,CONDSP,CLEVEL psect text ; SUBTTL 'MACRO pseudo-operator' ; ; Macro structure as saved in high memory: ; ; DSPTR: ; db STMDEF ; type = MACRO def ; dw len ; length of following block: ; db len,'name' ; macro name ; db nlocal ; number of local variables ; db 'body line 1',0 ; macro body, dummy params replaced by ; db 'body line 2',0 ; 80h + param number, local vars by ; db 'body line 3',0 ; 0C0h + var number ; db ... ; ; db EOF ; end of macro marker ; ; Macros are built first on low memory (following symbol table) ; and moved to upper memory when the final size is known. ; ; SYMPTR: ; db len,'name' ; macro name (old var name) ; db len,'arg1' ; dummy param list, needed only for scanning ; db len,'arg2' ; of macro definition body and will not be ; db len,'arg3' ; copied to high mem, len has the hi-bit ; db len,'arg4' ; set if it corresponds to a local var ; db ... ; ; db 0FFh ; end of args ; db nlocal ; number of local variables ; db 'body line 1',0 ; params and local variables replaced by ; db 'body line 2',0 ; single-byte code as explained above ; db 'body line 3',0 ; ; db ... ; ; db EOF ; end of macro marker ; ; Nested macros are allowed. However, nesting happens at execution time and ; not at definition time (i.e. an inner macro becomes defined only when the ; outer macro is executed). The macro generation code has to track the ; nesting level nevertheless to prevent exiting prematurely the macro ; definition mode when the ENDM of an inner macro is encountered. ; DEFMAC: call ID ;get macro name (ZAS type syntax) call ADDSYM ;add-it as symbol ld hl,(IDADR) ; get pointer to identifier (MACRO name) ld a,h or l jp z,OERROR ; ensure is present ld a,(NEWSYM) or a jr nz,NEWMAC ; branch if new symbol ; M80 allows macros to have the same name as existing symbols, ; or even existing macros. Here we do the same. ; Macros have priority over instruction mnemonics. ld a,(hl) ; get identity char and 1Fh ;0Fh jp z,OERROR ; error if name is invalid ld c,a ld b,0 inc bc ld de,(SYMPTR) ; for code @NEWMAC ld (IDADR),de ldir ; copy length + name NEWMAC: ld hl,(IDADR) ld (SYMPTR),hl ; remove new symbol from symbol table ld a,(hl) ; get length+flags and 1Fh ;0Fh ; remove flags, leave length ld (hl),a push hl ld (IDLEN),a inc hl ld de,IDBUF ld c,a ld b,0 ldir call FNDMAC ; is this a macro re-definition? jr c,NM1 ; branch if not ld a,STDEL ld (de),a ; else delete old macro ld a,(MACLVL) or a call z,GBCOL ; if at safe level, call garbage collector NM1: ld a,(IDLEN) pop hl ld c,a ld b,0 inc bc inc bc call MCHECK ; make sure we have enough memory dec bc jp c,WERROR add hl,bc ld (MACPTR),hl ; set macro build pointer ld (PARAMS),hl ; set pointer to parameters xor a ld (LCLFLG),a ; clear LOCAL flag for GETPRM call GNC ; get next character or a ; end of line? call nz,GETPRM ; get parameters if not xor a ld (LCOUNT),a ; reset LOCAL variable count ld hl,(MACPTR) ld (hl),0FFh ; set end of args marker inc hl ld (MACPTR),hl ld a,$MACRO ld (MACTYP),a ; remember type is MACRO INCDFL: ld hl,MDFLVL inc (hl) ; increase macro def level ret nz dec (hl) VERROR: ld a,'V' ; on overflow, set error flag ld (ERRFLG),a ret ; ; Get MACRO dummy parameters or LOCAL variables ; GETPRM: ld bc,RECMAX ; ensure enough available memory call MACCHK ; (RECMAX is a bit more than enough here, jp c,WERROR ; but that will save time and some bytes) call BACKUP GP0: call ID ; get identifier ld a,(IDLEN) or a ; valid identifier? jr nz,GP1 ; yes -> branch call OERROR ; no -> argument error jr GP2 GP1: ld c,a ld b,0 ld hl,IDBUF ld de,(MACPTR) ld a,(LCLFLG) or c ; set MSB of length if LOCAL variable name ld (de),a ; store length inc de ldir ld (MACPTR),de ld hl,LCOUNT inc (hl) ; increase LOCAL variable count GP2: call GNC cp ',' ; more params? jr z,GP0 ; loop if yes or a ; end of line? ret z ; return Z if yes jp BACKUP ; else backup to scanned char and return ; ; Store macro, called from the main thread while in macro def mode. ; MSTORE: ld hl,(PTR1) push hl ; save current PTR1 call ID ; get first identifier cp ':' jr z,MST1 ; skip if label cp '&' ; test for possible param substitution jr nz,MST0 ld hl,(PTR1) MSKIP: ld a,(hl) ; if yes, ignore everything or a ; up to the next delimiter jr z,MSKP1 cp ' ' jr z,MSKP1 cp TAB jr z,MSKP1 inc hl cp ':' jr z,MSKP1 jr MSKIP MSKP1: ld (PTR1),hl jr MST2 MST0: call FNDOPC ; lookup opcode jr nc,MST3 ; branch if found jr MST2 MST1: call GNC ; skip over delimiter MST2: call ID ; try second identifier call FNDOPC ; lookup opcode jp c,MST8 ; branch if not found MST3: ld e,(hl) inc hl ld d,(hl) inc hl ld a,(hl) cp 27 ; class 27? (pseudo-ops) jp nz,MST8 ; branch if not ld a,e cp 24 ; MACRO/REPT/IRP/IRPC? jp z,MST7 ; branch if yes - nested macro definition cp 25 ; ENDM? jr z,MST4 ; branch if yes cp 27 ; LOCAL? jp nz,MST8 ; branch if not ; LOCAL ld a,(MACTYP) cp $MACRO jp nz,MST8 ; only MACROs can have LOCALs ld a,(MDFLVL) dec a jp nz,MST8 ; don't process it if inside a nested macro pop hl ; drop saved PTR1 ld hl,(MACPTR) dec hl ld a,(hl) inc a ; test for 0FFh ret nz ; too late, LOCAL not allowed here ld a,80h ld (LCLFLG),a ; set LOCAL flag for GETPRM ld (MACPTR),hl call GNC ; get next character or a ; end of line? jp z,OERROR ; error if yes call GETPRM ; else get parameter list ld hl,(MACPTR) ld (hl),0FFh ; set new end of args inc hl ld (MACPTR),hl ret MST4: ld hl,MDFLVL dec (hl) ; decrement macro level jp nz,MST8 ; ENDM ld a,(MACLVL) or a call z,GBCOL ; if at safe level, call garbage collector pop hl ; drop saved PTR1 ld hl,(MACPTR) ld (hl),EOF ; set end of macro marker inc hl ld (MACPTR),hl ld a,(MACTYP) ; check macro type cp $MACRO jr nz,MST6 ; branch if REPT/IRP/IRPC - execute immediately ; end MACRO definition ld de,(SYMPTR) ; begin of macro build area MST5: ld a,(de) inc de inc a ; 0FFh marks end of param list jr nz,MST5 ; find begin of macro body (use CPIR?) ld hl,(MACPTR) push hl or a sbc hl,de ; obtain length ld c,l ld b,h ld de,(DSPTR) pop hl push bc dec hl dec de lddr ; copy to high memory ld a,(LCOUNT) ld (de),a ; save number of LOCAL variables dec de ld hl,(SYMPTR) ld a,(hl) ; get length ld c,a ld b,0 inc bc push bc add hl,bc dec hl lddr ; copy name + len pop hl pop bc add hl,bc inc hl ; account for LOCAL variable count field ex de,hl ld (hl),d dec hl ld (hl),e ; set length dec hl ld (hl),STMDEF ; struct type = macro def ld (DSPTR),hl ld hl,(SYMPTR) ld (hl),0 ; restore end of symbol table marker ret MST6: ; REPT/IRP/IRPC execution ld de,(MACBGN) ld hl,(MACPTR) push hl or a sbc hl,de ; obtain length ld c,l ld b,h ld de,(DSPTR) pop hl push bc dec hl dec de lddr ; copy to high memory pop bc ex de,hl xor a ld (hl),a ; clear text index dec hl ld (hl),a dec hl ld a,(CLEVEL) ld (hl),a ; store current conditional level dec hl ld a,(MACTYP) ld (hl),a ; set macro type dec hl inc bc inc bc inc bc inc bc ld (hl),b dec hl ld (hl),c ; set length dec hl ld (hl),STMEXP ; struct type = macro expansion ld (DSPTR),hl ld hl,(SYMPTR) ld (hl),0 ; restore end of symbol table marker ld hl,MACLVL inc (hl) ; start macro execution ret nz dec (hl) jp VERROR MST7: call INCDFL MST8: ld a,' ' ld (ERRFLG),a pop hl ld (PTR1),hl ; restore old PTR1 ld bc,0 MST9: ld a,(hl) inc hl inc bc ; compute length, including trailing null or a jr nz,MST9 call MACCHK ; check for enough space jp c,WERROR ; error if out of memory ld hl,(PTR1) ld de,(MACPTR) push de ldir ; copy line to macro body ld (MACPTR),de dec hl ; point back to trailing null ex (sp),hl ld (PTR1),hl ld a,(ERRFLG) ; save ERRFLG, as MSCAN may generate spurious push af ; errors when testing for valid identifiers call MSCAN ; scan line and encode params pop af ld (ERRFLG),a ; restore original ERRFLG xor a ld (de),a ; end line with a null inc de ld (MACPTR),de pop hl ld (PTR1),hl ; restore old record pointer ret ; ; MSCAN - Scan line for dummy parameters and local variables, ; and replace them with one-byte codes. ; ; Code for dummy parameter = 80h + param ordinal ; Code for local variable = C0h + label ordinal ; MSCAN: ld e,l ; get dest address in DE ld d,h ; (will overwrite src contents) S0: ld a,(hl) ; get char from line or a ret z ; if end of line, return cp ';' jr z,S14 ; branch if start of comment cp 27H ;' jr z,S9 ; branch if start of quoted string cp '""' ; (inside a string any parameters jr z,S9 ; must be preceded by an ampersand) cp ' ' jr z,S1 ; store blanks directly cp TAB jr z,S1 S1A: call SUBST ; test for parameter and substitute if found jr S0 ; loop S1: ld (de),a ; store char inc hl ; advance pointers inc de jr S0 ; loop S9: ; quoted string ld (de),a ; store quote char inc de ld c,a S10: inc hl S11: ld a,(hl) ; get next char or a ret z ; if end of line, return cp c ; quote? jr z,S1 ; exit this loop if yes cp '&' ; ampersand? jr nz,S12 ; branch if not push bc call SUBST ; else match parameter pop bc jr S11 ; loop S12: ld (de),a ; store char inc de ; advance pointer jr S10 ; and loop S14: ; comment inc hl cp (hl) ; do not store comments that begin with ret z ; two semicolons dec hl S15: ld (de),a ; store comment, but do not perform any or a ; parameter substitutions ret z inc de inc hl ld a,(hl) jr S15 ; ; SUBST - Test for dummy parameter or local variable name ; and substitute with the corresponding value if found. ; SUBST: push af cp '&' ; ampersand? jr nz,S5A inc hl ; skip it if yes (but remember it) S5A: push hl ld (PTR1),hl ; remember start of possible identifier call ID ld a,(IDLEN) or a ; valid identifier? jr z,S2 ; branch if not push de ld c,a ; C = identifier length ld b,80h ; B = parameter code ld hl,(PARAMS) ; HL = dummy parameter list S5: ld a,(hl) ; get dummy parameter length inc a ; test for 0FFh jr z,S3 ; parameter not found, exit loop dec a bit 7,a ; hi-bit set? jr z,S8 ; branch if not bit 6,b ; first time? jr nz,S8 ; branch if not ld b,0C0h ; else make B = LOCAL label code S8: and 7Fh ; kill hi-bit cp c jr nz,S4 ; not same length push hl push bc inc hl ld b,a ld de,IDBUF S6: ld a,(de) cp (hl) ; compare strings (both already in uppercase) jr nz,S7 ; not same inc hl inc de djnz S6 pop bc pop hl ; matches pop de ld a,b ld (de),a ; store parameter code inc de pop hl pop af ld hl,(PTR1) ; point past identifier ret S7: pop bc pop hl ld a,(hl) and 7Fh ; get length S4: ld e,a ld d,0 add hl,de inc hl ; point to next parameter inc b jr S5 ; loop to match next S3: pop de ; parameter not found, restore registers pop hl pop af cp '&' ; first char was ampersand? jr nz,S3A ; branch if not ld (de),a ; else restore it inc de S3A: ld b,0 ldir ; copy identifier name S3B: ld a,(hl) call VALID ; and any other following VALID chars ret c ld (de),a inc hl inc de jr S3B S2: pop hl ; not an identifier, restore registers pop af cp '&' ; first char was ampersand? jr nz,S2A ; branch if not ld (de),a ; else restore it inc de S2A: ld a,(hl) ; copy char ld (de),a inc hl inc de ret ; SUBTTL 'MACRO processing' ; ; EXPMAC - Expand MACRO. ; Called with HL pointing to macro body in dynamic area ; (e.g. as returned by FNDMAC). ; ; Macro expansion structure as saved in high memory: ; ; db STMEXP ; type = MACRO expansion ; dw len ; length of the following block: ; db $MACRO ; macro type ; db clevel ; saved conditional level ; dw index ; text index ; dw local ; first/base number for LOCAL variables ; dw macptr ; pointer to macro def ; db len,'arg1' ; arg 1 ; db len,'arg2' ; arg 2 ; db ... ; ; db 0FFh ; end of args ; EXPMAC: ld bc,6 call MCHECK jp c,WERROR ld a,(hl) ; get number of LOCAL variables inc hl ; point to start of macro text push hl ld bc,(LCLNUM) ; get LOCAL base number into BC ld l,a ld h,0 add hl,bc ld (LCLNUM),hl ; save number of next LOCAL variable pop de ld hl,(SYMPTR) ld (MACBGN),hl ld (hl),c ; store base number of LOCAL labels inc hl ld (hl),b inc hl ld (hl),e ; store pointer to macro def inc hl ld (hl),d inc hl ld (MACPTR),hl call GNC or a call nz,GETARG ; get arguments ld (hl),0FFh ; end of args inc hl ld (MACPTR),hl ld a,$MACRO ld (MACTYP),a jp MST6 ; exit via common code ; ; Get comma-separated list of arguments ; GETARG: ld bc,RECMAX ; ensure enough available memory call MACCHK ; (RECMAX is a bit more than enough here, jp c,WERROR ; but will save some bytes and time) call BACKUP GT0: ld de,(MACPTR) push de inc de ; placeholder for length call GETSTR ; get next argument ex de,hl ld (MACPTR),hl pop de push af or a sbc hl,de dec hl ld a,l ld (de),a ; store length pop af jr c,GT1 call GNC or a jr z,GT1 cp ',' jr z,GT0 GT1: ld hl,(MACPTR) ret ; ; FNDMAC - Find MACRO ; FNDMAC: ld c,STMDEF ; record type = macro def call FNDREC FNDM1: ret c ; not found push hl inc hl ; skip type inc hl ; and record length inc hl ld a,(IDLEN) cp (hl) ; compare name length jr nz,FNDM3 ; branch if not same inc hl ld b,a ld de,IDBUF FNDM2: ld a,(de) cp (hl) jr nz,FNDM3 inc hl inc de djnz FNDM2 pop de ; found, HL now points past macro name ret ; return with CY clear FNDM3: pop hl ld c,STMDEF call FNDNXT jr FNDM1 ; ; Reading from MACRO/REPT/IRP/IRPC ; GNRMAC: ld c,STMEXP call FNDREC ; find top-level executing macro jr nc,GNR1 ; branch if found xor a ; if not found (should not happen!) ld (MACLVL),a ; reset the macro execution level jp GNR ; and switch back to reading from file GNR1: inc hl ; skip struct type inc hl ; and length fields inc hl ld a,(hl) ; get macro type inc hl inc hl ; skip over saved conditional level cp $MACRO jr z,XMACRO ; execute MACRO cp $REPT jp z,XREPT ; execute REPT cp $IRP jp z,XIRP ; execute IRP cp $IRPC jp z,XIRPC ; execute IRPC jp OERROR ; should never happen ; ; Read from MACRO and expand arguments ; XMACRO: push hl ; save pointer ld c,(hl) ; get char index inc hl ld b,(hl) inc hl ld e,(hl) ; get LOCAL base number inc hl ld d,(hl) ld (LBASE),de inc hl ld e,(hl) ; get pointer to macro definition inc hl ld d,(hl) inc hl ld (ARGS),hl ; save pointer to arguments ex de,hl add hl,bc ; index into macro text ld a,(hl) ; get char cp EOF jp z,XEND ; end of text = end of macro ld de,REC ld (PTR1),de ld a,RECMAX-1 ld (RCOUNT),a XM1: ld a,(hl) ; get char from macro text inc hl inc bc ; advance index or a ; test for coded dummy parameter jp p,XM3 ; branch if not parameter push hl ; else save text pointer push bc ld hl,(ARGS) ; get start address of argument list sub 80h-1 ; get param number cp 40h+1 jr nc,XM8 ; branch if local variable ld b,a ; B = param number XM6: ld a,(hl) ; get length inc a ; 0FFh marks end of arguments jr z,XM4 ; branch if not found dec a inc hl ; point to string djnz XM5 ; count until found or a jr z,XM7 ; if null argument ld b,a XM2: ld a,(hl) call SAVREC ; expand argument inc hl djnz XM2 XM7: pop bc pop hl ; restore text pointers jr XM1 ; continue with text XM5: ld e,a ; get length into DE ld d,0 add hl,de ; point to next argument jr XM6 ; loop XM8: sub 40h+1 ; get label ordinal ld e,a ld d,0 ld hl,(LBASE) add hl,de ex de,hl push de ld a,'?' call SAVREC ; create label of type '??nnnn' call SAVREC pop de ld hl,(PTR1) ld c,d call XM9 ld c,e call XM9 ld (PTR1),hl pop bc pop hl jr XM1 XM9: ld a,(RCOUNT) sub 2 ret c ld (RCOUNT),a ld a,c jp CNV2HX XM4: pop bc pop hl ; not found, restore text pointers jr XM1 ; and loop (will expand as null string) XM3: call SAVREC ; save char in REC buffer or a ; end of line? jr nz,XM1 ; loop if not ld hl,(PTR1) ld (hl),a ; append null in case line was truncated ld hl,REC ld (PTR1),hl pop hl ld (hl),c ; update text index inc hl ld (hl),b ret SAVREC: push hl ld e,a ld hl,RCOUNT ld a,(hl) or a ; limit reached? jr z,ST1 ; return if yes dec a ld (hl),a ld hl,(PTR1) ld (hl),e ; store char in buffer inc hl ld (PTR1),hl ST1: ld a,e pop hl ret ; ; Read from REPT, no arguments to expand ; XREPT: push hl ld c,(hl) ; get char index inc hl ld b,(hl) inc hl ld e,(hl) ; get count inc hl ld d,(hl) ld a,d or e ; counter reached zero? jp z,XEND ; if yes, end execution inc hl add hl,bc ; index into macro text ld a,(hl) cp EOF ; end of text? jr z,XR3 ; branch if yes, start next iteration ld de,REC XR1: ld a,(hl) ; no arg substitution for REPT inc hl inc bc ld (de),a ; and so no need to check for REC buf overflow or a jr z,XR2 inc de jr XR1 XR2: pop hl ld (hl),c ; update text index inc hl ld (hl),b ret XR3: pop hl ; next iteration push hl xor a ld (hl),a ; reset text index inc hl ld (hl),a inc hl ld c,(hl) inc hl ld b,(hl) dec bc ; decrement iteration counter ld (hl),b dec hl ld (hl),c pop hl jr XREPT ; restart execution ; ; Read from IRP, expand single argument ; XIRP: push hl ld c,(hl) ; get text index inc hl ld b,(hl) inc hl ld a,(hl) ; get argument index inc hl ; point to argument list inc a XP1: ld e,(hl) ; get arg length inc e jp z,XEND ; arg list exhausted dec a jr z,XP2 ld d,0 add hl,de ; point to next argument jr XP1 XP2: ld (ARGS),hl XP3: ld a,(hl) inc hl inc a jr nz,XP3 ; find start of body text add hl,bc ; index into macro text ld a,(hl) ; get char cp EOF ; end of text? jr z,XP7 ; branch if yes, start next iteration ld de,REC ld (PTR1),de ld a,RECMAX-1 ld (RCOUNT),a XP4: ld a,(hl) ; get char from macro text inc hl inc bc ; advance index or a ; test for coded dummy parameter jp p,XP5 ; branch if not parameter push hl push bc ld hl,(ARGS) ; else expand parameter ld a,(hl) inc a jr z,XP6 ; if no arguments dec a jr z,XP6 ; if null argument ld b,a inc hl XP9: ld a,(hl) call SAVREC ; expand argument inc hl djnz XP9 XP6: pop bc pop hl jr XP4 XP5: call SAVREC ; save char in REC buffer or a ; end of line? jr nz,XP4 ; loop if not ld hl,(PTR1) ld (hl),a ; append null in case line was truncated ld hl,REC ld (PTR1),hl pop hl ld (hl),c ; update text index inc hl ld (hl),b ret XP7: pop hl ; next iteration push hl xor a ld (hl),a ; reset text index inc hl ld (hl),a inc hl inc (hl) ; advance arg index pop hl jr XIRP ; restart execution ; ; Read from IRPC, expand single argument ; XIRPC: push hl ; save pointer ld c,(hl) ; get text index inc hl ld b,(hl) inc hl ld a,(hl) ; get string index inc hl cp (hl) ; compare with string length jr nc,XEND ; end if string exhausted push hl inc hl ld e,a ld d,0 add hl,de ; index into string ld a,(hl) ; get string char ld (ARGS),a ; save it pop hl ld e,(hl) ld d,0 inc hl add hl,de ; skip string, point to begin of body text add hl,bc ; index into macro text ld a,(hl) ; get char cp EOF ; end of text? jr z,XC4 ; branch if yes, start next iteration ld de,REC XC1: ld a,(hl) ; get char from macro text inc hl inc bc ; advance index or a ; test for coded dummy parameter jp p,XC3 ; branch if not parameter ld a,(ARGS) ; else use string char XC3: ld (de),a ; save char in REC buf (no need for ovfl check) or a ; end of line? jr z,XC2 ; branch if yes inc de jr XC1 ; else loop for more XC2: pop hl ld (hl),c ; update text index inc hl ld (hl),b ret XC4: pop hl ; next iteration push hl xor a ld (hl),a ; reset text index inc hl ld (hl),a inc hl inc (hl) ; advance string index pop hl jr XIRPC ; restart execution ; ; End of MACRO/REPT/IRP/IRPC execution ; XEND: pop hl dec hl dec hl dec hl dec hl dec hl call MFREE ; release storage ld hl,MACLVL dec (hl) ; decrease macro execution level call z,GBCOL ; if zero, perform garbage collection jp GNR ; switch input back to GNR ; SUBTTL 'EXITM pseudo-operator' ; ; EXITM ; ENDMAC: ld c,STMEXP call FNDREC ; find top-level executing macro jp c,OERROR ; error if not found: EXITM without MACRO push hl inc hl inc hl inc hl inc hl ld a,(hl) ; get saved conditional level ld (CLEVEL),a ld hl,CNDSTK ld e,a ld d,0 sbc hl,de ; note CY is still clear ld (CONDSP),hl ; restore conditional stack pointer pop hl call MFREE ; release storage ld hl,MACLVL dec (hl) ; decrement macro execution level call z,GBCOL ret ; SUBTTL 'REPT pseudo-operator' ; ; REPT structure as saved in high memory: ; ; db STMEXP ; type = MACRO expansion ; dw len ; length of following block: ; db $REPT ; macro type ; db clevel ; saved conditional level ; dw index ; text index ; dw count ; REPT argument ; db 'body line 1',0 ; macro ; db 'body line 2',0 ; body ; db ... ; ; db EOF ; end of macro ; DFREPT: ld bc,2 call MCHECK jp c,WERROR call EVALNEW ; get argument ld a,(EVMODE) or a jr z,DFR1 call RELERR ; can't be reloc ld de,0 ; null counter to prevent execution DFR1: ex de,hl ld hl,(SYMPTR) ld (PARAMS),hl ld (hl),0FFh ; no parameters inc hl ld (MACBGN),hl ld (hl),e ; store counter value inc hl ld (hl),d inc hl ld (MACPTR),hl ; init macro def pointer ld a,$REPT ld (MACTYP),a jp INCDFL ; increase macro def level ; SUBTTL 'IRP pseudo-operator' ; IRP structure as saved in high memory: ; ; db STMEXP ; type = MACRO expansion ; dw len ; length of the following block: ; db $IRP ; macro type ; db clevel ; saved conditional level ; dw index ; text index ; db argidx ; argument index ; db len,'arg1' ; IRP argument 1 ; db len,'arg2' ; IRP argument 2 ; db ... ; ; db 0FFh ; end of argument list ; db 'body line 1',0 ; macro ; db 'body line 2',0 ; body ; db ... ; ; db EOF ; end of macro ; DFIRP: ld bc,RECMAX ; hopefully enough - if there are a lot call MCHECK ; of '%vars' then argument list can jp c,WERROR ; quickly grow in size!!! ld hl,(SYMPTR) ld (MACPTR),hl ld (PARAMS),hl call ID ld a,(IDLEN) or a ; valid identifier? jr nz,DP1 ; yes -> branch call OERROR ; no -> argument error ld de,(MACPTR) jr DP2 DP1: ld c,a ld b,0 ld hl,IDBUF ld de,(MACPTR) ld (de),a ; store length inc de ldir DP2: ld a,0FFh ld (de),a ; 0FFh marks end of params inc de ld (MACBGN),de ; set start address of body inc a ld (de),a ; arg index inc de ld (MACPTR),de call GNC cp ',' jp nz,OERROR ; comma must follow call GNC cp '<' ; then '<' jp nz,OERROR DP3: ld de,(MACPTR) push de inc de ; length placeholder call GETSTR ex de,hl ld (MACPTR),hl pop de push af or a sbc hl,de dec hl ld a,l ld (de),a ; store length pop af jr c,DP4 ; argument error, stop scanning? call GNC or a jr z,DP4 ; argument error (missing '>') and exit loop cp '>' jr z,DP5 ; success, exit loop cp ',' jr z,DP3 call BACKUP jr DP3 DP4: call OERROR DP5: ld hl,(MACPTR) ld (hl),0FFh ; end of argument list inc hl ld (MACPTR),hl ld a,$IRP ld (MACTYP),a jp INCDFL ; increase macro def level ; ; Skip blanks and get a single argument string until a comma or ; another blank char is found. Angle brackets and/or quotes can ; be used to delimit a substring containing spaces or commas. ; GETSTR: ld c,0 ; bracket nesting count call GNC or a ret z ld hl,(PTR1) dec hl GS0: ld a,(hl) ; since GNC converts char to uppercase inc hl or a jr z,GS9 cp ' ' jr z,GS6 ; delimiters are spaces, cp TAB jr z,GS6 ; tabs cp ',' jr z,GS6 ; commas cp ';' jr z,GS6 ; and semicolons cp '<' jr z,GS1 ; opening bracket starts a substring cp '>' jr z,GS2 cp '%' ; percent sign followed by a var name or expr jr z,GS5 ; expands to a numeric value cp '!' jr nz,GS7 ; exclamation mark means escape char ld a,(hl) inc hl or a scf jr z,GS8 GS7: ld (de),a ; store char inc de cp 27H ;' jr z,GS3 cp '""' jr nz,GS0 GS3: ld b,a ; get quote char into B GS4: ld a,(hl) inc hl or a scf jr z,GS8 ; missing closing quote ld (de),a inc de cp b jr nz,GS4 ; loop until closing quote found jr GS0 GS1: inc c dec c ; first opening bracket? jr nz,GS11 inc c ; yes: increment nesting level jr GS0 ; and remove the bracket GS11: inc c ; no: increment nesting level jr GS7 ; but keep the bracket GS2: inc c ; check bracket nesting dec c ; error if zero ;; scf ;; do not tag as error here (caller will) jr z,GS8 ; '>' without '<' dec c ; decrement nesting level jr nz,GS7 ; keep the bracket if not zero inc hl ; else remove the bracket or a ; and finish jr GS8 GS6: inc c dec c ; store delimiters jr nz,GS7 ; if inside substring GS8: dec hl ld (PTR1),hl ld a,0 ld (de),a ret GS9: inc c ; end of arg string, dec c ; check for balanced brackets jr z,GS8 scf ; missing '>' jr GS8 GS5: ; expand %expr push bc push de ld (PTR1),hl call EVALNEW ; evaluate expression ld a,(EVMODE) ; get mode and 0C0h+EXTSYM jr z,GS51 call RELERR ; value must be Absolute and EXTSYM jr z,GS51 ld hl,0 ; value is 0 for External GS51: pop de call CVTNUM ; convert to string ld hl,(PTR1) pop bc jp GS0 ; ; Convert value in HL to ASCII string using the current base. ; Store the result at (DE). ; CVTNUM: push de ld de,(RADIX) ld bc,NUMBUF ld a,0FFh ; end marker ld (bc),a inc bc CN1: push bc xor a ld b,16 ; HL=HL/E, remainder in A DLOOP: add hl,hl rla cp e jr c,DNEXT sub e inc l DNEXT: djnz DLOOP pop bc ld (bc),a ; save remainder inc bc ld a,h or l ; result 0? jr nz,CN1 ; loop if not pop de CN2: dec bc ld a,(bc) ; check digit cp 0FFh ; 0FFh is flag for no more ret z ; if so, return add a,90h ; else convert to ASCII daa adc a,40h daa ld (de),a ; store digit inc de jr CN2 ; go back for more ; SUBTTL 'IRPC pseudo-operator' ; IRPC structure as saved in high memory: ; ; db STMEXP ; type = MACRO expansion ; dw len ; length of the following block: ; db $IRPC ; macro type ; db clevel ; saved conditional level ; dw index ; text index ; db stridx ; string index ; db len,'string' ; IRPC argument string ; db 'body line 1',0 ; macro ; db 'body line 2',0 ; body ; db EOF ; end of macro ; DFIRPC: ld bc,RECMAX call MCHECK jp c,WERROR ld hl,(SYMPTR) ld (MACPTR),hl ; save macro build pointer ld (PARAMS),hl call ID ; get dummy parameter ld a,(IDLEN) or a ; valid identifier? jr nz,DC1 ; yes -> branch call OERROR ; no -> argument error ld de,(MACPTR) jr DC2 DC1: ld c,a ld b,0 ld hl,IDBUF ld de,(MACPTR) ld (de),a ; store length inc de ldir DC2: ld a,0FFh ld (de),a ; 0FFh marks end of params inc de ld (MACBGN),de ; set start address of body inc a ld (de),a ; string index inc de ld (MACPTR),de call GNC cp ',' jp nz,OERROR ; comma must follow ld de,(MACPTR) push de ; remember address of length field inc de call GNC ld hl,(PTR1) dec hl ; reload the original first char ld a,(hl) ; as GNC converted it to uppercase inc hl cp '<' ld bc,1 ; B = length, C = bracket nesting level jr z,DC5 dec c DC3: ld (de),a inc b inc de ld a,(hl) or a jr z,DC4 cp ' ' jr z,DC4 cp TAB jr z,DC4 cp ',' jr z,DC4 cp ';' jr z,DC4 inc hl jr DC3 DC4: ld (PTR1),hl ld (MACPTR),de pop hl ; pop address of length field ld (hl),b ; save length of string ld a,$IRPC ld (MACTYP),a jp INCDFL ; increase macro def level DC5: ld a,(hl) or a jr z,DC8 inc hl cp '>' jr z,DC7 cp '<' jr nz,DC6 inc c DC6: ld (de),a inc b inc de jr DC5 DC7: dec c jr nz,DC6 jr DC4 DC8: call ERRQ ; missing closing '>' jr DC4 psect data MDFLVL: defb 0 ; nested MACRO definition counter MACTYP: defs 1 ; type of macro being defined MACLVL: defb 0 ; macro execution level MACBGN: defs 2 ; begin of macro body MACPTR: defs 2 ; macro build ptr PARAMS: defs 2 ; pointer to dummy parameters during MACRO build ARGS: defs 2 ; pointer to argument list during MACRO expansion LCLFLG: defs 1 ; LOCAL variable flag LCLNUM: defs 2 ; LOCAL label number for next MACRO expansion LBASE: defs 2 ; LOCAL label base number for executing MACRO LCOUNT: defs 1 ; number of LOCAL variables in a MACRO RCOUNT: defs 1 ; REC char count during MACRO expansion NUMBUF: defs 17 ; buffer for numeric conv. (max size = binary base) ; end ",12458,True,2850.92958406421,median "class ltcl_text2tab_utils_test definition for testing final risk level harmless duration short. private section. constants c_tab like cl_abap_char_utilities=>horizontal_tab value cl_abap_char_utilities=>horizontal_tab. constants c_crlf like cl_abap_char_utilities=>cr_lf value cl_abap_char_utilities=>cr_lf. constants c_lf like cl_abap_char_utilities=>newline value cl_abap_char_utilities=>newline. * ==== TESTING === methods validate_date_format_spec for testing. methods function_exists for testing. methods get_safe_struc_descr for testing raising zcx_text2tab_error. methods describe_struct for testing raising zcx_text2tab_error. methods describe_struct_with_descr for testing raising zcx_text2tab_error. methods describe_struct_ignoring for testing raising zcx_text2tab_error. methods describe_struct_deep for testing raising zcx_text2tab_error. methods break_to_lines for testing. methods build_rename_map for testing. methods create_standard_table_of for testing raising zcx_text2tab_error. methods parse_deep_address for testing raising zcx_text2tab_error. methods get_struc_field_value_by_name for testing raising zcx_text2tab_error. methods check_version_fits for testing. methods check_version_fits_w_pre for testing. endclass. ********************************************************************** * Implementation ********************************************************************** class ltcl_text2tab_utils_test implementation. method build_rename_map. data lx type ref to zcx_text2tab_error. try. clear lx. zcl_text2tab_utils=>build_rename_map( 1234 ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>assert_equals( act = lx->code exp = 'WY' ). endtry. cl_abap_unit_assert=>assert_not_initial( act = lx ). try. clear lx. zcl_text2tab_utils=>build_rename_map( 'abc' ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>assert_equals( act = lx->code exp = 'WR' ). endtry. cl_abap_unit_assert=>assert_not_initial( act = lx ). data lt_fields type zcl_text2tab_utils=>tt_field_name_map. data lt_map_act type zcl_text2tab_utils=>tt_field_name_map. data lt_map_exp type zcl_text2tab_utils=>tt_field_name_map. field-symbols like line of lt_map_exp. append initial line to lt_fields assigning . -from = 'some_field'. -to = 'tstring'. append initial line to lt_fields assigning . -from = 'some_field2'. -to = 'tstring2'. append initial line to lt_map_exp assigning . -from = 'SOME_FIELD'. -to = 'TSTRING'. append initial line to lt_map_exp assigning . -from = 'SOME_FIELD2'. -to = 'TSTRING2'. "" Table based try. lt_map_act = zcl_text2tab_utils=>build_rename_map( lt_fields ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>fail( lx->get_text( ) ). endtry. cl_abap_unit_assert=>assert_equals( act = lt_map_act exp = lt_map_exp ). "" string based data lv_fields type string. lv_fields = 'some_field:tstring;some_field2:tstring2;;'. try. lt_map_act = zcl_text2tab_utils=>build_rename_map( lv_fields ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>fail( lx->get_text( ) ). endtry. cl_abap_unit_assert=>assert_equals( act = lt_map_act exp = lt_map_exp ). endmethod. method break_to_lines. data: lt_act type string_table, lt_exp type string_table. append 'line1' to lt_exp. append 'line2' to lt_exp. lt_act = zcl_text2tab_utils=>break_to_lines( i_text = 'line1' && c_crlf && 'line2' i_begin_comment = space ). cl_abap_unit_assert=>assert_equals( act = lt_act exp = lt_exp ). lt_act = zcl_text2tab_utils=>break_to_lines( i_text = 'line1' && c_lf && 'line2' i_begin_comment = space ). cl_abap_unit_assert=>assert_equals( act = lt_act exp = lt_exp ). "" with comment line clear lt_exp. append 'not a comment 1' to lt_exp. append 'not a comment 2' to lt_exp. lt_act = zcl_text2tab_utils=>break_to_lines( i_text = '*a comment' && c_lf && 'not a comment 1' && c_lf && 'not a comment 2' && c_lf && cl_abap_char_utilities=>newline i_begin_comment = '*' ). cl_abap_unit_assert=>assert_equals( act = lt_act exp = lt_exp ). endmethod. "" break_to_lines. method get_safe_struc_descr. data: ls_dummy type abap_compdescr, lt_dummy type standard table of abap_compdescr, lo_td_exp type ref to cl_abap_structdescr, lo_td_act type ref to cl_abap_structdescr, lx type ref to zcx_text2tab_error. lo_td_exp ?= cl_abap_typedescr=>describe_by_data( ls_dummy ). "" Positive lo_td_act = zcl_text2tab_utils=>get_safe_struc_descr( ls_dummy ). cl_abap_unit_assert=>assert_equals( act = lo_td_act->absolute_name exp = lo_td_exp->absolute_name ). lo_td_act = zcl_text2tab_utils=>get_safe_struc_descr( lt_dummy ). cl_abap_unit_assert=>assert_equals( act = lo_td_act->absolute_name exp = lo_td_exp->absolute_name ). "" Positive with class lo_td_act = zcl_text2tab_utils=>get_safe_struc_descr( lo_td_exp ). cl_abap_unit_assert=>assert_equals( act = lo_td_act->absolute_name exp = lo_td_exp->absolute_name ). lo_td_act = zcl_text2tab_utils=>get_safe_struc_descr( cl_abap_tabledescr=>create( lo_td_exp ) ). cl_abap_unit_assert=>assert_equals( act = lo_td_act->absolute_name exp = lo_td_exp->absolute_name ). "" Negative try. lo_td_act = zcl_text2tab_utils=>get_safe_struc_descr( 'ABC' ). cl_abap_unit_assert=>fail( ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>assert_equals( exp = 'PE' act = lx->code ). endtry. "" Negative with class try. lo_td_act = zcl_text2tab_utils=>get_safe_struc_descr( me ). cl_abap_unit_assert=>fail( ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>assert_equals( exp = 'PE' act = lx->code ). endtry. endmethod. ""get_safe_struc_descr method validate_date_format_spec. data: lx type ref to zcx_text2tab_error, lv_date_format type zcl_text2tab_parser=>ty_date_format. do 3 times. case sy-index. when 1. lv_date_format = 'XXX'. when 2. lv_date_format = 'DM'. when 3. lv_date_format = 'DMY='. when 4. lv_date_format = 'DMM-'. endcase. try. zcl_text2tab_utils=>validate_date_format_spec( lv_date_format ). cl_abap_unit_assert=>fail( ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>assert_equals( act = lx->code exp = 'UD' ). "" Unsupported date format endtry. enddo. endmethod. ""validate_date_format_spec method function_exists. data lv_act type abap_bool. lv_act = zcl_text2tab_utils=>function_exists( 'CONVERSION_EXIT_?????_OUTPUT' ). cl_abap_unit_assert=>assert_equals( act = lv_act exp = abap_false ). lv_act = zcl_text2tab_utils=>function_exists( 'CONVERSION_EXIT_ALPHA_OUTPUT' ). cl_abap_unit_assert=>assert_equals( act = lv_act exp = abap_true ). "" cached lv_act = zcl_text2tab_utils=>function_exists( 'CONVERSION_EXIT_ALPHA_OUTPUT' ). cl_abap_unit_assert=>assert_equals( act = lv_act exp = abap_true ). endmethod. method describe_struct. types: begin of lty_dummy, talpha type veri_alpha, end of lty_dummy. data ld_struc type ref to cl_abap_structdescr. data ls_dummy type lty_dummy. data lt_descr type zcl_text2tab_utils=>tt_comp_descr. data lx type ref to zcx_text2tab_error. field-symbols like line of lt_descr. ld_struc ?= cl_abap_structdescr=>describe_by_data( ls_dummy ). lt_descr = zcl_text2tab_utils=>describe_struct( i_struc = ld_struc i_ignore_nonflat = abap_false ). cl_abap_unit_assert=>assert_equals( act = lines( lt_descr ) exp = 1 ). read table lt_descr assigning index 1. cl_abap_unit_assert=>assert_equals( act = -name exp = 'TALPHA' ). cl_abap_unit_assert=>assert_equals( act = -edit_mask exp = 'ALPHA' ). cl_abap_unit_assert=>assert_equals( act = -output_length exp = 10 ). "" Test 2: fail on non-flat components types: begin of lty_dummy2, tstruc type lty_dummy, end of lty_dummy2. data ls_dummy2 type lty_dummy2. try. ld_struc ?= cl_abap_structdescr=>describe_by_data( ls_dummy2 ). lt_descr = zcl_text2tab_utils=>describe_struct( i_struc = ld_struc i_ignore_nonflat = abap_false ). cl_abap_unit_assert=>fail( ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>assert_equals( act = lx->code exp = 'SF' ). endtry. endmethod. method describe_struct_with_descr. types: begin of lty_dummy, mandt type mandt, char type c length 8, date type datum, end of lty_dummy. data ld_struc type ref to cl_abap_structdescr. data ls_dummy type lty_dummy. data lt_descr type zcl_text2tab_utils=>tt_comp_descr. field-symbols like line of lt_descr. ld_struc ?= cl_abap_structdescr=>describe_by_data( ls_dummy ). lt_descr = zcl_text2tab_utils=>describe_struct( i_struc = ld_struc i_with_descr_in_lang = 'E' ). cl_abap_unit_assert=>assert_equals( act = lines( lt_descr ) exp = 3 ). read table lt_descr assigning index 1. cl_abap_unit_assert=>assert_equals( act = -description exp = 'Client' ). read table lt_descr assigning index 2. cl_abap_unit_assert=>assert_equals( act = -description exp = '' ). read table lt_descr assigning index 3. cl_abap_unit_assert=>assert_equals( act = -description exp = 'Date' ). endmethod. method describe_struct_ignoring. types: begin of lty_dummy, talpha type veri_alpha, tstruc type abap_compdescr, "" Deep end of lty_dummy. data ld_struc type ref to cl_abap_structdescr. data ls_dummy type lty_dummy. data lt_descr type zcl_text2tab_utils=>tt_comp_descr. field-symbols like line of lt_descr. ld_struc ?= cl_abap_structdescr=>describe_by_data( ls_dummy ). lt_descr = zcl_text2tab_utils=>describe_struct( i_struc = ld_struc i_ignore_nonflat = abap_true ). cl_abap_unit_assert=>assert_equals( act = lines( lt_descr ) exp = 2 ). read table lt_descr assigning index 1. cl_abap_unit_assert=>assert_equals( act = -name exp = 'TALPHA' ). cl_abap_unit_assert=>assert_equals( act = -edit_mask exp = 'ALPHA' ). cl_abap_unit_assert=>assert_equals( act = -output_length exp = 10 ). cl_abap_unit_assert=>assert_equals( act = -ignore exp = abap_false ). read table lt_descr assigning index 2. cl_abap_unit_assert=>assert_equals( act = -name exp = 'TSTRUC' ). cl_abap_unit_assert=>assert_equals( act = -edit_mask exp = '' ). cl_abap_unit_assert=>assert_equals( act = -output_length exp = 0 ). cl_abap_unit_assert=>assert_equals( act = -ignore exp = abap_true ). endmethod. method describe_struct_deep. types: begin of lty_dummy, talpha type veri_alpha, tstruc type abap_compdescr, "" Deep end of lty_dummy. data ld_struc type ref to cl_abap_structdescr. data ls_dummy type lty_dummy. data lt_descr type zcl_text2tab_utils=>tt_comp_descr. field-symbols like line of lt_descr. ld_struc ?= cl_abap_structdescr=>describe_by_data( ls_dummy ). lt_descr = zcl_text2tab_utils=>describe_struct( i_struc = ld_struc i_is_deep = abap_true ). cl_abap_unit_assert=>assert_equals( act = lines( lt_descr ) exp = 2 ). read table lt_descr assigning index 1. cl_abap_unit_assert=>assert_equals( act = -name exp = 'TALPHA' ). cl_abap_unit_assert=>assert_equals( act = -edit_mask exp = 'ALPHA' ). cl_abap_unit_assert=>assert_equals( act = -output_length exp = 10 ). cl_abap_unit_assert=>assert_equals( act = -ignore exp = abap_false ). read table lt_descr assigning index 2. cl_abap_unit_assert=>assert_equals( act = -name exp = 'TSTRUC' ). cl_abap_unit_assert=>assert_equals( act = -edit_mask exp = '' ). cl_abap_unit_assert=>assert_equals( act = -output_length exp = 0 ). cl_abap_unit_assert=>assert_equals( act = -ignore exp = abap_false ). endmethod. method check_version_fits. cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.2' i_required_version = 'v2.2.2' ) ). cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.2' i_required_version = 'v2.1.2' ) ). cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.2' i_required_version = 'v1.0.0' ) ). cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.3.0' i_required_version = 'v2.2.5' ) ). cl_abap_unit_assert=>assert_false( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.1.2' i_required_version = 'v2.2.2' ) ). cl_abap_unit_assert=>assert_false( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v1.0.0' i_required_version = 'v2.2.2' ) ). cl_abap_unit_assert=>assert_false( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.5' i_required_version = 'v2.3.0' ) ). cl_abap_unit_assert=>assert_false( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.2' i_required_version = 'v2.2.3' ) ). cl_abap_unit_assert=>assert_false( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.2' i_required_version = 'v2.2.30' ) ). cl_abap_unit_assert=>assert_false( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.2' i_required_version = 'v2.3.1' ) ). cl_abap_unit_assert=>assert_false( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.2' i_required_version = 'v3.0.0' ) ). cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.3' i_required_version = 'v2.2.2' ) ). cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.2.30' i_required_version = 'v2.2.2' ) ). cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.3.1' i_required_version = 'v2.2.2' ) ). cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v3.0.0' i_required_version = 'v2.2.2' ) ). cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.1.10' i_required_version = 'v2.1.7' ) ). endmethod. method check_version_fits_w_pre. cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.1.10-beta' i_required_version = 'v2.1.7' ) ). cl_abap_unit_assert=>assert_false( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.1.10-beta' i_required_version = 'v2.1.10' ) ). cl_abap_unit_assert=>assert_true( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.1.10-beta' i_required_version = 'v2.1.10-alpha' ) ). cl_abap_unit_assert=>assert_false( zcl_text2tab_utils=>check_version_fits( i_current_version = 'v2.1.10-beta' i_required_version = 'v2.1.10-gamma' ) ). endmethod. method get_struc_field_value_by_name. data lx type ref to zcx_text2tab_error. data: lv_a type string, lv_b type d, begin of ls_dummy, a type string, b type d, end of ls_dummy. ls_dummy-a = 'ABC'. ls_dummy-b = '20190820'. zcl_text2tab_utils=>get_struc_field_value_by_name( exporting i_struc = ls_dummy i_field_name = 'A' importing e_value = lv_a ). cl_abap_unit_assert=>assert_equals( act = lv_a exp = 'ABC' ). zcl_text2tab_utils=>get_struc_field_value_by_name( exporting i_struc = ls_dummy i_field_name = 'B' importing e_value = lv_b ). cl_abap_unit_assert=>assert_equals( act = lv_b exp = '20190820' ). try. zcl_text2tab_utils=>get_struc_field_value_by_name( i_struc = ls_dummy i_field_name = 'C' ). cl_abap_unit_assert=>fail( ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>assert_equals( act = lx->code exp = 'FN' ). endtry. endmethod. method parse_deep_address. data ls_parsed type zcl_text2tab_utils=>ty_deep_address. data lx type ref to zcx_text2tab_error. ls_parsed = zcl_text2tab_utils=>parse_deep_address( 'filename[id=@headid]' ). cl_abap_unit_assert=>assert_equals( act = ls_parsed-location exp = 'filename' ). cl_abap_unit_assert=>assert_equals( act = ls_parsed-key_field exp = 'ID' ). cl_abap_unit_assert=>assert_equals( act = ls_parsed-ref_field exp = 'HEADID' ). cl_abap_unit_assert=>assert_equals( act = ls_parsed-key_value exp = '' ). ls_parsed = zcl_text2tab_utils=>parse_deep_address( 'filename[id=12345]' ). cl_abap_unit_assert=>assert_equals( act = ls_parsed-location exp = 'filename' ). cl_abap_unit_assert=>assert_equals( act = ls_parsed-key_field exp = 'ID' ). cl_abap_unit_assert=>assert_equals( act = ls_parsed-ref_field exp = '' ). cl_abap_unit_assert=>assert_equals( act = ls_parsed-key_value exp = '12345' ). try. zcl_text2tab_utils=>parse_deep_address( 'XYZ' ). cl_abap_unit_assert=>fail( ). catch zcx_text2tab_error into lx. cl_abap_unit_assert=>assert_equals( act = lx->code exp = 'IA' ). endtry. endmethod. method create_standard_table_of. types: begin of lty_dummy, a type c length 1, b type i, end of lty_dummy. data ls_dummy type lty_dummy. data lt_dummy type hashed table of lty_dummy with unique key a. data lr_dref type ref to data. data lo_type type ref to cl_abap_typedescr. data lo_ttype type ref to cl_abap_tabledescr. lr_dref = zcl_text2tab_utils=>create_standard_table_of( ls_dummy ). lo_type = cl_abap_typedescr=>describe_by_data_ref( lr_dref ). cl_abap_unit_assert=>assert_equals( act = lo_type->kind exp = cl_abap_typedescr=>kind_table ). lo_ttype ?= lo_type. cl_abap_unit_assert=>assert_equals( act = lo_ttype->table_kind exp = cl_abap_tabledescr=>tablekind_std ). lr_dref = zcl_text2tab_utils=>create_standard_table_of( lt_dummy ). lo_type = cl_abap_typedescr=>describe_by_data_ref( lr_dref ). cl_abap_unit_assert=>assert_equals( act = lo_type->kind exp = cl_abap_typedescr=>kind_table ). lo_ttype ?= lo_type. cl_abap_unit_assert=>assert_equals( act = lo_ttype->table_kind exp = cl_abap_tabledescr=>tablekind_std ). lr_dref = zcl_text2tab_utils=>create_standard_table_of( cl_abap_typedescr=>describe_by_data( ls_dummy ) ). lo_type = cl_abap_typedescr=>describe_by_data_ref( lr_dref ). cl_abap_unit_assert=>assert_equals( act = lo_type->kind exp = cl_abap_typedescr=>kind_table ). lo_ttype ?= lo_type. cl_abap_unit_assert=>assert_equals( act = lo_ttype->table_kind exp = cl_abap_tabledescr=>tablekind_std ). endmethod. endclass. ",5581,False,1307.9820865746585,median "/** * BigInteger * * An ActionScript 3 implementation of BigInteger (light version) * Copyright (c) 2007 Henri Torgemane * * Derived from: * The jsbn library, Copyright (c) 2003-2005 Tom Wu * * See LICENSE.txt for full license information. */ package com.hurlant.math { import com.hurlant.crypto.prng.Random; import com.hurlant.util.Hex; import com.hurlant.util.Memory; import flash.utils.ByteArray; use namespace bi_internal; public class BigInteger { public static const DB:int = 30; // number of significant bits per chunk public static const DV:int = (1<0) { if (p>p)>0) { m = true; r = d.toString(36); } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { r += d.toString(36); } } } return m?r:""0""; } public function toArray(array:ByteArray):uint { const k:int = 8; const km:int = (1<<8)-1; var d:int = 0; var i:int = t; var p:int = DB-(i*DB)%k; var m:Boolean = false; var c:int = 0; if (i-->0) { if (p>p)>0) { m = true; array.writeByte(d); c++; } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { array.writeByte(d); c++; } } } return c; } /** * best-effort attempt to fit into a Number. * precision can be lost if it just can't fit. */ public function valueOf():Number { if (s==-1) { return -negate().valueOf(); } var coef:Number = 1; var value:Number = 0; for (var i:uint=0;i v, - if this < v, 0 if equal */ public function compareTo(v:BigInteger):int { var r:int = s - v.s; if (r!=0) { return r; } var i:int = t; r = i-v.t; if (r!=0) { return r; } while (--i >=0) { r=a[i]-v.a[i]; if (r != 0) return r; } return 0; } /** * returns bit length of the integer x */ bi_internal function nbits(x:int):int { var r:int = 1; var t:int; if ((t=x>>>16) != 0) { x = t; r += 16; } if ((t=x>>8) != 0) { x = t; r += 8; } if ((t=x>>4) != 0) { x = t; r += 4; } if ((t=x>>2) != 0) { x = t; r += 2; } if ((t=x>>1) != 0) { x = t; r += 1; } return r; } /** * returns the number of bits in this */ public function bitLength():int { if (t<=0) return 0; return DB*(t-1)+nbits(a[t-1]^(s&DM)); } /** * * @param v * @return this % v * */ public function mod(v:BigInteger):BigInteger { var r:BigInteger = nbi(); abs().divRemTo(v,null,r); if (s<0 && r.compareTo(ZERO)>0) { v.subTo(r,r); } return r; } /** * this^e % m, 0 <= e < 2^32 */ public function modPowInt(e:int, m:BigInteger):BigInteger { var z:IReduction; if (e<256 || m.isEven()) { z = new ClassicReduction(m); } else { z = new MontgomeryReduction(m); } return exp(e, z); } /** * copy this to r */ bi_internal function copyTo(r:BigInteger):void { for (var i:int = t-1; i>=0; --i) { r.a[i] = a[i]; } r.t = t; r.s = s; } /** * set from integer value ""value"", -DV <= value < DV */ bi_internal function fromInt(value:int):void { t = 1; s = (value<0)?-1:0; if (value>0) { a[0] = value; } else if (value<-1) { a[0] = value+DV; } else { t = 0; } } /** * set from ByteArray and length, * starting a current position * If length goes beyond the array, pad with zeroes. */ bi_internal function fromArray(value:ByteArray, length:int, unsigned:Boolean = false):void { var p:int = value.position; var i:int = p+length; var sh:int = 0; const k:int = 8; t = 0; s = 0; while (--i >= p) { var x:int = i DB) { a[t-1] |= (x&((1<<(DB-sh))-1))<>(DB-sh); } else { a[t-1] |= x<= DB) sh -= DB; } if (!unsigned && (value[0]&0x80)==0x80) { s = -1; if (sh > 0) { a[t-1] |= ((1<<(DB-sh))-1)<0 && a[t-1]==c) { --t; } } /** * r = this << n*DB */ bi_internal function dlShiftTo(n:int, r:BigInteger):void { var i:int; for (i=t-1; i>=0; --i) { r.a[i+n] = a[i]; } for (i=n-1; i>=0; --i) { r.a[i] = 0; } r.t = t+n; r.s = s; } /** * r = this >> n*DB */ bi_internal function drShiftTo(n:int, r:BigInteger):void { var i:int; for (i=n; i=0; --i) { r.a[i+ds+1] = (a[i]>>cbs)|c; c = (a[i]&bm)<=0; --i) { r.a[i] = 0; } r.a[ds] = c; r.t = t+ds+1; r.s = s; r.clamp(); } /** * r = this >> n */ bi_internal function rShiftTo(n:int, r:BigInteger):void { r.s = s; var ds:int = n/DB; if (ds >= t) { r.t = 0; return; } var bs:int = n%DB; var cbs:int = DB-bs; var bm:int = (1<>bs; var i:int; for (i=ds+1; i>bs; } if (bs>0) { r.a[t-ds-1] |= (s&bm)<>= DB; } if (v.t < t) { c -= v.s; while (i< t) { c+= a[i]; r.a[i++] = c&DM; c >>= DB; } c += s; } else { c += s; while (i < v.t) { c -= v.a[i]; r.a[i++] = c&DM; c >>= DB; } c -= v.s; } r.s = (c<0)?-1:0; if (c<-1) { r.a[i++] = DV+c; } else if (c>0) { r.a[i++] = c; } r.t = i; r.clamp(); } /** * am: Compute w_j += (x*this_i), propagates carries, * c is initial carry, returns final carry. * c < 3*dvalue, x < 2*dvalue, this_i < dvalue */ bi_internal function am(i:int,x:int,w:BigInteger,j:int,c:int,n:int):int { var xl:int = x&0x7fff; var xh:int = x>>15; while(--n >= 0) { var l:int = a[i]&0x7fff; var h:int = a[i++]>>15; var m:int = xh*l + h*xl; l = xl*l + ((m&0x7fff)<<15)+w.a[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w.a[j++] = l&0x3fffffff; } return c; } /** * r = this * v, r != this,a (HAC 14.12) * ""this"" should be the larger one if appropriate */ bi_internal function multiplyTo(v:BigInteger, r:BigInteger):void { var x:BigInteger = abs(); var y:BigInteger = v.abs(); var i:int = x.t; r.t = i+y.t; while (--i >= 0) { r.a[i] = 0; } for (i=0; i=0) r.a[i] = 0; for (i=0; i= DV) { r.a[i+x.t] -= DV; r.a[i+x.t+1] = 1; } } if (r.t>0) { r.a[r.t-1] += x.am(i, x.a[i], r, 2*i, 0, 1); } r.s = 0; r.clamp(); } /** * divide this by m, quotient and remainder to q, r (HAC 14.20) * r != q, this != m. q or r may be null. */ bi_internal function divRemTo(m:BigInteger, q:BigInteger = null, r:BigInteger = null):void { var pm:BigInteger = m.abs(); if (pm.t <= 0) return; var pt:BigInteger = abs(); if (pt.t < pm.t) { if (q!=null) q.fromInt(0); if (r!=null) copyTo(r); return; } if (r==null) r = nbi(); var y:BigInteger = nbi(); var ts:int = s; var ms:int = m.s; var nsh:int = DB-nbits(pm.a[pm.t-1]); // normalize modulus if (nsh>0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys:int = y.t; var y0:int = y.a[ys-1]; if (y0==0) return; var yt:Number = y0*(1<1)?y.a[ys-2]>>F2:0); var d1:Number = FV/yt; var d2:Number = (1<=0) { r.a[r.t++] = 1; r.subTo(t,r); } ONE.dlShiftTo(ys,t); t.subTo(y,y); // ""negative"" y so we can replace sub with am later. while(y.t= 0) { // Estimate quotient digit var qd:int = (r.a[--i]==y0)?DM:Number(r.a[i])*d1+(Number(r.a[i-1])+e)*d2; if ((r.a[i]+= y.am(0, qd, r, j, 0, ys))0) { r.rShiftTo(nsh, r); // Denormalize remainder } if (ts<0) { ZERO.subTo(r,r); } } /** * return ""-1/this % 2^DB""; useful for Mont. reduction * justification: * xy == 1 (mod n) * xy = 1+km * xy(2-xy) = (1+km)(1-km) * x[y(2-xy)] = 1-k^2.m^2 * x[y(2-xy)] == 1 (mod m^2) * if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 * should reduce x and y(2-xy) by m^2 at each step to keep size bounded * [XXX unit test the living shit out of this.] */ bi_internal function invDigit():int { if (t<1) return 0; var x:int = a[0]; if ((x&1)==0) return 0; var y:int = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf )*y)) &0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y)) &0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints // XXX 48 bit ints? Whaaaa? is there an implicit float conversion in here? y = (y*(2-x*y%DV))%DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?DV-y:-y; } /** * true iff this is even */ bi_internal function isEven():Boolean { return ((t>0)?(a[0]&1):s) == 0; } /** * this^e, e < 2^32, doing sqr and mul with ""r"" (HAC 14.79) */ bi_internal function exp(e:int, z:IReduction):BigInteger { if (e > 0xffffffff || e < 1) return ONE; var r:BigInteger = nbi(); var r2:BigInteger = nbi(); var g:BigInteger = z.convert(this); var i:int = nbits(e)-1; g.copyTo(r); while(--i>=0) { z.sqrTo(r, r2); if ((e&(1<0) { z.mulTo(r2,g,r); } else { var t:BigInteger = r; r = r2; r2 = t; } } return z.revert(r); } bi_internal function intAt(str:String, index:int):int { return parseInt(str.charAt(index), 36); } protected function nbi():* { return new BigInteger; } /** * return bigint initialized to value */ public static function nbv(value:int):BigInteger { var bn:BigInteger = new BigInteger; bn.fromInt(value); return bn; } // Functions above are sufficient for RSA encryption. // The stuff below is useful for decryption and key generation public static const lowprimes:Array = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; public static const lplim:int = (1<<26)/lowprimes[lowprimes.length-1]; public function clone():BigInteger { var r:BigInteger = new BigInteger; this.copyTo(r); return r; } /** * * @return value as integer * */ public function intValue():int { if (s<0) { if (t==1) { return a[0]-DV; } else if (t==0) { return -1; } } else if (t==1) { return a[0]; } else if (t==0) { return 0; } // assumes 16 < DB < 32 return ((a[1]&((1<<(32-DB))-1))<>24; } /** * * @return value as short (assumes DB>=16) * */ public function shortValue():int { return (t==0)?s:(a[0]<<16)>>16; } /** * * @param r * @return x s.t. r^x < DV * */ protected function chunkSize(r:Number):int { return Math.floor(Math.LN2*DB/Math.log(r)); } /** * * @return 0 if this ==0, 1 if this >0 * */ public function sigNum():int { if (s<0) { return -1; } else if (t<=0 || (t==1 && a[0]<=0)) { return 0; } else{ return 1; } } /** * * @param b: radix to use * @return a string representing the integer converted to the radix. * */ protected function toRadix(b:uint=10):String { if (sigNum()==0 || b<2 || b>32) return ""0""; var cs:int = chunkSize(b); var a:Number = Math.pow(b, cs); var d:BigInteger = nbv(a); var y:BigInteger = nbi(); var z:BigInteger = nbi(); var r:String = """"; divRemTo(d, y, z); while (y.sigNum()>0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } /** * * @param s a string to convert from using radix. * @param b a radix * */ protected function fromRadix(s:String, b:int = 10):void { fromInt(0); var cs:int = chunkSize(b); var d:Number = Math.pow(b, cs); var mi:Boolean = false; var j:int = 0; var w:int = 0; for (var i:int=0;i= cs) { dMultiply(d); dAddOffset(w,0); j=0; w=0; } } if (j>0) { dMultiply(Math.pow(b,j)); dAddOffset(w,0); } if (mi) { BigInteger.ZERO.subTo(this, this); } } // XXX function fromNumber not written yet. /** * * @return a byte array. * */ public function toByteArray():ByteArray { var i:int = t; var r:ByteArray = new ByteArray; r[0] = s; var p:int = DB-(i*DB)%8; var d:int; var k:int=0; if (i-->0) { if (p>p)!=(s&DM)>>p) { r[k++] = d|(s<<(DB-p)); } while (i>=0) { if(p<8) { d = (a[i]&((1<>(p+=DB-8); } else { d = (a[i]>>(p-=8))&0xff; if (p<=0) { p += DB; --i; } } if ((d&0x80)!=0) d|=-256; if (k==0 && (s&0x80)!=(d&0x80)) ++k; if (k>0 || d!=s) r[k++] = d; } } return r; } public function equals(a:BigInteger):Boolean { return compareTo(a)==0; } public function min(a:BigInteger):BigInteger { return (compareTo(a)<0)?this:a; } public function max(a:BigInteger):BigInteger { return (compareTo(a)>0)?this:a; } /** * * @param a a BigInteger to perform the operation with * @param op a Function implementing the operation * @param r a BigInteger to store the result of the operation * */ protected function bitwiseTo(a:BigInteger, op:Function, r:BigInteger):void { var i:int; var f:int; var m:int = Math.min(a.t, t); for (i=0; i>= 16; r += 16; } if ((x&0xff) == 0) { x>>= 8; r += 8; } if ((x&0xf) == 0) { x>>= 4; r += 4; } if ((x&0x3) == 0) { x>>= 2; r += 2; } if ((x&0x1) == 0) ++r; return r; } /** * * @return index of lowest 1-bit (or -1 if none) * */ public function getLowestSetBit():int { for (var i:int=0;i=t) { return s!=0; } return ((a[j]&(1<<(n%DB)))!=0); } /** * * @param n * @param op * @return this op (1<>=DB; } if (a.t < t) { c += a.s; while (i>= DB; } c += s; } else { c += s; while (i>= DB; } c += a.s; } r.s = (c<0)?-1:0; if (c>0) { r.a[i++] = c; } else if (c<-1) { r.a[i++] = DV+c; } r.t = i; r.clamp(); } /** * * @param a * @return this + a * */ public function add(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; addTo(a,r); return r; } /** * * @param a * @return this - a * */ public function subtract(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; subTo(a,r); return r; } /** * * @param a * @return this * a * */ public function multiply(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; multiplyTo(a,r); return r; } /** * * @param a * @return this / a * */ public function divide(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, r, null); return r; } public function remainder(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, null, r); return r; } /** * * @param a * @return [this/a, this%a] * */ public function divideAndRemainder(a:BigInteger):Array { var q:BigInteger = new BigInteger; var r:BigInteger = new BigInteger; divRemTo(a, q, r); return [q,r]; } /** * * this *= n, this >=0, 1 < n < DV * * @param n * */ bi_internal function dMultiply(n:int):void { a[t] = am(0, n-1, this, 0, 0, t); ++t; clamp(); } /** * * this += n << w words, this >= 0 * * @param n * @param w * */ bi_internal function dAddOffset(n:int, w:int):void { while (t<=w) { a[t++] = 0; } a[w] += n; while (a[w] >= DV) { a[w] -= DV; if (++w >= t) { a[t++] = 0; } ++a[w]; } } /** * * @param e * @return this^e * */ public function pow(e:int):BigInteger { return exp(e, new NullReduction); } /** * * @param a * @param n * @param r = lower n words of ""this * a"", a.t <= n * */ bi_internal function multiplyLowerTo(a:BigInteger, n:int, r:BigInteger):void { var i:int = Math.min(t+a.t, n); r.s = 0; // assumes a, this >= 0 r.t = i; while (i>0) { r.a[--i]=0; } var j:int; for (j=r.t-t;i 0 * */ bi_internal function multiplyUpperTo(a:BigInteger, n:int, r:BigInteger):void { --n; var i:int = r.t = t+a.t-n; r.s = 0; // assumes a,this >= 0 while (--i>=0) { r.a[i] = 0; } for (i=Math.max(n-t,0);i 1) { var g2:BigInteger = new BigInteger; z.sqrTo(g[1], g2); while (n<=km) { g[n] = new BigInteger; z.mulTo(g2, g[n-2], g[n]); n += 2; } } var j:int = e.t-1; var w:int; var is1:Boolean = true; var r2:BigInteger = new BigInteger; var t:BigInteger; i = nbits(e.a[j])-1; while (j>=0) { if (i>=k1) { w = (e.a[j]>>(i-k1))&km; } else { w = (e.a[j]&((1<<(i+1))-1))<<(k1-i); if (j>0) { w |= e.a[j-1]>>(DB+i-k1); } } n = k; while ((w&1)==0) { w >>= 1; --n; } if ((i -= n) <0) { i += DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n>1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n>0) { z.sqrTo(r, r2); } else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j>=0 && (e.a[j]&(1<0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.sigNum()>0) { if ((i = x.getLowestSetBit()) >0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) >0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g>0) { y.lShiftTo(g, y); } return y; } /** * * @param n * @return this % n, n < 2^DB * */ protected function modInt(n:int):int { if (n<=0) return 0; var d:int = DV%n; var r:int = (s<0)?n-1:0; if (t>0) { if (d==0) { r = a[0]%n; } else { for (var i:int=t-1;i>=0;--i) { r = (d*r+a[i])%n; } } } return r; } /** * * @param m * @return 1/this %m (HAC 14.61) * */ public function modInverse(m:BigInteger):BigInteger { var ac:Boolean = m.isEven(); if ((isEven()&&ac) || m.sigNum()==0) { return BigInteger.ZERO; } var u:BigInteger = m.clone(); var v:BigInteger = clone(); var a:BigInteger = nbv(1); var b:BigInteger = nbv(0); var c:BigInteger = nbv(0); var d:BigInteger = nbv(1); while (u.sigNum()!=0) { while (u.isEven()) { u.rShiftTo(1,u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if (!b.isEven()) { b.subTo(m,b); } b.rShiftTo(1,b); } while (v.isEven()) { v.rShiftTo(1,v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if (!d.isEven()) { d.subTo(m,d); } d.rShiftTo(1,d); } if (u.compareTo(v)>=0) { u.subTo(v,u); if (ac) { a.subTo(c,a); } b.subTo(d,b); } else { v.subTo(u,v); if (ac) { c.subTo(a,c); } d.subTo(b,d); } } if (v.compareTo(BigInteger.ONE) != 0) { return BigInteger.ZERO; } if (d.compareTo(m) >= 0) { return d.subtract(m); } if (d.sigNum()<0) { d.addTo(m,d); } else { return d; } if (d.sigNum()<0) { return d.add(m); } else { return d; } } /** * * @param t * @return primality with certainty >= 1-.5^t * */ public function isProbablePrime(t:int):Boolean { var i:int; var x:BigInteger = abs(); if (x.t == 1 && x.a[0]<=lowprimes[lowprimes.length-1]) { for (i=0;i>1; if (t>lowprimes.length) { t = lowprimes.length; } var a:BigInteger = new BigInteger; for (var i:int=0;ibits) subTo(BigInteger.ONE.shiftLeft(bits-1),this); } } } } ",12287,True,2699.903878442227,median "-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2013-2020, Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- -- Gen_Keyboard -------------------------------------------------------------------------------------------------------------------- -- Generates the SDL.Events.Keyboards.ads file. -- Makefile should call this and redirect the output to the correct file in $TOP/gen_src/sdl-events-keyboards.ads. -------------------------------------------------------------------------------------------------------------------- with Ada.Unchecked_Conversion; with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Characters.Latin_1; with Utils; use Utils; with Scancodes; use Scancodes; procedure Gen_Keyboard is package Latin_1 renames Ada.Characters.Latin_1; function To_US (Str : in String) return Unbounded_String renames To_Unbounded_String; License : constant array (Positive range <>) of Unbounded_String := (To_US (""Copyright (c) 2013-2020, Luke A. Guest""), To_US (""""), To_US (""This software is provided 'as-is', without any express or implied""), To_US (""warranty. In no event will the authors be held liable for any damages""), To_US (""arising from the use of this software.""), To_US (""""), To_US (""Permission is granted to anyone to use this software for any purpose,""), To_US (""including commercial applications, and to alter it and redistribute it""), To_US (""freely, subject to the following restrictions:""), To_US (""""), To_US ("" 1. The origin of this software must not be misrepresented; you must not""), To_US ("" claim that you wrote the original software. If you use this software""), To_US ("" in a product, an acknowledgment in the product documentation would be""), To_US ("" appreciated but is not required.""), To_US (""""), To_US ("" 2. Altered source versions must be plainly marked as such, and must not be""), To_US ("" misrepresented as being the original software.""), To_US (""""), To_US ("" 3. This notice may not be removed or altered from any source""), To_US ("" distribution."")); Package_Description : constant array (Positive range <>) of Unbounded_String := (To_US (""SDL.Events.Keyboards""), To_US (""""), To_US (""Keyboard specific events."")); type Mapping_States is (Output, New_Line, Comment); package Scan_Codes_IO is new Integer_IO (Scan_Codes); use Scan_Codes_IO; type Scan_Code_Mapping is record State : Mapping_States := Output; Name : Unbounded_String := Null_Unbounded_String; Code : Scan_Codes := Scan_Codes'Last; Comment : Unbounded_String := Null_Unbounded_String; end record; New_Line_Scan_Code : constant Scan_Code_Mapping := (New_Line, Null_Unbounded_String, Scan_Codes'Last, Null_Unbounded_String); type Scan_Code_Tables is array (Positive range <>) of Scan_Code_Mapping; Scan_Code_Table : constant Scan_Code_Tables := ((Output, To_US (""Scan_Code_Unknown""), 0, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_A""), 4, Null_Unbounded_String), (Output, To_US (""Scan_Code_B""), 5, Null_Unbounded_String), (Output, To_US (""Scan_Code_C""), 6, Null_Unbounded_String), (Output, To_US (""Scan_Code_D""), 7, Null_Unbounded_String), (Output, To_US (""Scan_Code_E""), 8, Null_Unbounded_String), (Output, To_US (""Scan_Code_F""), 9, Null_Unbounded_String), (Output, To_US (""Scan_Code_G""), 10, Null_Unbounded_String), (Output, To_US (""Scan_Code_H""), 11, Null_Unbounded_String), (Output, To_US (""Scan_Code_I""), 12, Null_Unbounded_String), (Output, To_US (""Scan_Code_J""), 13, Null_Unbounded_String), (Output, To_US (""Scan_Code_K""), 14, Null_Unbounded_String), (Output, To_US (""Scan_Code_L""), 15, Null_Unbounded_String), (Output, To_US (""Scan_Code_M""), 16, Null_Unbounded_String), (Output, To_US (""Scan_Code_N""), 17, Null_Unbounded_String), (Output, To_US (""Scan_Code_O""), 18, Null_Unbounded_String), (Output, To_US (""Scan_Code_P""), 19, Null_Unbounded_String), (Output, To_US (""Scan_Code_Q""), 20, Null_Unbounded_String), (Output, To_US (""Scan_Code_R""), 21, Null_Unbounded_String), (Output, To_US (""Scan_Code_S""), 22, Null_Unbounded_String), (Output, To_US (""Scan_Code_T""), 23, Null_Unbounded_String), (Output, To_US (""Scan_Code_U""), 24, Null_Unbounded_String), (Output, To_US (""Scan_Code_V""), 25, Null_Unbounded_String), (Output, To_US (""Scan_Code_W""), 26, Null_Unbounded_String), (Output, To_US (""Scan_Code_X""), 27, Null_Unbounded_String), (Output, To_US (""Scan_Code_Y""), 28, Null_Unbounded_String), (Output, To_US (""Scan_Code_Z""), 29, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_1""), 30, Null_Unbounded_String), (Output, To_US (""Scan_Code_2""), 31, Null_Unbounded_String), (Output, To_US (""Scan_Code_3""), 32, Null_Unbounded_String), (Output, To_US (""Scan_Code_4""), 33, Null_Unbounded_String), (Output, To_US (""Scan_Code_5""), 34, Null_Unbounded_String), (Output, To_US (""Scan_Code_6""), 35, Null_Unbounded_String), (Output, To_US (""Scan_Code_7""), 36, Null_Unbounded_String), (Output, To_US (""Scan_Code_8""), 37, Null_Unbounded_String), (Output, To_US (""Scan_Code_9""), 38, Null_Unbounded_String), (Output, To_US (""Scan_Code_0""), 39, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Return""), 40, Null_Unbounded_String), (Output, To_US (""Scan_Code_Escape""), 41, Null_Unbounded_String), (Output, To_US (""Scan_Code_Backspace""), 42, Null_Unbounded_String), (Output, To_US (""Scan_Code_Tab""), 43, Null_Unbounded_String), (Output, To_US (""Scan_Code_Space""), 44, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Minus""), 45, Null_Unbounded_String), (Output, To_US (""Scan_Code_Equals""), 46, Null_Unbounded_String), (Output, To_US (""Scan_Code_Left_Bracket""), 47, Null_Unbounded_String), (Output, To_US (""Scan_Code_Right_Bracket""), 48, Null_Unbounded_String), (Output, To_US (""Scan_Code_Back_Slash""), 49, Null_Unbounded_String), (Output, To_US (""Scan_Code_Non_US_Hash""), 50, Null_Unbounded_String), (Output, To_US (""Scan_Code_Semi_Colon""), 51, Null_Unbounded_String), (Output, To_US (""Scan_Code_Apostrophe""), 52, Null_Unbounded_String), (Output, To_US (""Scan_Code_Grave""), 53, Null_Unbounded_String), (Output, To_US (""Scan_Code_Comma""), 54, Null_Unbounded_String), (Output, To_US (""Scan_Code_Period""), 55, Null_Unbounded_String), (Output, To_US (""Scan_Code_Slash""), 56, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Caps_Lock""), 57, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_F1""), 58, Null_Unbounded_String), (Output, To_US (""Scan_Code_F2""), 59, Null_Unbounded_String), (Output, To_US (""Scan_Code_F3""), 60, Null_Unbounded_String), (Output, To_US (""Scan_Code_F4""), 61, Null_Unbounded_String), (Output, To_US (""Scan_Code_F5""), 62, Null_Unbounded_String), (Output, To_US (""Scan_Code_F6""), 63, Null_Unbounded_String), (Output, To_US (""Scan_Code_F7""), 64, Null_Unbounded_String), (Output, To_US (""Scan_Code_F8""), 65, Null_Unbounded_String), (Output, To_US (""Scan_Code_F9""), 66, Null_Unbounded_String), (Output, To_US (""Scan_Code_F10""), 67, Null_Unbounded_String), (Output, To_US (""Scan_Code_F11""), 68, Null_Unbounded_String), (Output, To_US (""Scan_Code_F12""), 69, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Print_Screen""), 70, Null_Unbounded_String), (Output, To_US (""Scan_Code_Scroll_Lock""), 71, Null_Unbounded_String), (Output, To_US (""Scan_Code_Pause""), 72, Null_Unbounded_String), (Output, To_US (""Scan_Code_Insert""), 73, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Home""), 74, Null_Unbounded_String), (Output, To_US (""Scan_Code_Page_Up""), 75, Null_Unbounded_String), (Output, To_US (""Scan_Code_Delete""), 76, Null_Unbounded_String), (Output, To_US (""Scan_Code_End""), 77, Null_Unbounded_String), (Output, To_US (""Scan_Code_Page_Down""), 78, Null_Unbounded_String), (Output, To_US (""Scan_Code_Right""), 79, Null_Unbounded_String), (Output, To_US (""Scan_Code_Left""), 80, Null_Unbounded_String), (Output, To_US (""Scan_Code_Down""), 81, Null_Unbounded_String), (Output, To_US (""Scan_Code_Up""), 82, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Num_Lock_Clear""), 83, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_KP_Divide""), 84, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Multiply""), 85, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Minus""), 86, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Plus""), 87, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Enter""), 88, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_1""), 89, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_2""), 90, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_3""), 91, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_4""), 92, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_5""), 93, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_6""), 94, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_7""), 95, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_8""), 96, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_9""), 97, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_0""), 98, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Period""), 99, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Non_US_Back_Slash""), 100, Null_Unbounded_String), (Output, To_US (""Scan_Code_Application""), 101, Null_Unbounded_String), (Output, To_US (""Scan_Code_Power""), 102, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Equals""), 103, Null_Unbounded_String), (Output, To_US (""Scan_Code_F13""), 104, Null_Unbounded_String), (Output, To_US (""Scan_Code_F14""), 105, Null_Unbounded_String), (Output, To_US (""Scan_Code_F15""), 106, Null_Unbounded_String), (Output, To_US (""Scan_Code_F16""), 107, Null_Unbounded_String), (Output, To_US (""Scan_Code_F17""), 108, Null_Unbounded_String), (Output, To_US (""Scan_Code_F18""), 109, Null_Unbounded_String), (Output, To_US (""Scan_Code_F19""), 110, Null_Unbounded_String), (Output, To_US (""Scan_Code_F20""), 111, Null_Unbounded_String), (Output, To_US (""Scan_Code_F21""), 112, Null_Unbounded_String), (Output, To_US (""Scan_Code_F22""), 113, Null_Unbounded_String), (Output, To_US (""Scan_Code_F23""), 114, Null_Unbounded_String), (Output, To_US (""Scan_Code_F24""), 115, Null_Unbounded_String), (Output, To_US (""Scan_Code_Execute""), 116, Null_Unbounded_String), (Output, To_US (""Scan_Code_Help""), 117, Null_Unbounded_String), (Output, To_US (""Scan_Code_Menu""), 118, Null_Unbounded_String), (Output, To_US (""Scan_Code_Select""), 119, Null_Unbounded_String), (Output, To_US (""Scan_Code_Stop""), 120, Null_Unbounded_String), (Output, To_US (""Scan_Code_Again""), 121, Null_Unbounded_String), (Output, To_US (""Scan_Code_Undo""), 122, Null_Unbounded_String), (Output, To_US (""Scan_Code_Cut""), 123, Null_Unbounded_String), (Output, To_US (""Scan_Code_Copy""), 124, Null_Unbounded_String), (Output, To_US (""Scan_Code_Paste""), 125, Null_Unbounded_String), (Output, To_US (""Scan_Code_Find""), 126, Null_Unbounded_String), (Output, To_US (""Scan_Code_Mute""), 127, Null_Unbounded_String), (Output, To_US (""Scan_Code_Volume_Up""), 128, Null_Unbounded_String), (Output, To_US (""Scan_Code_Volume_Down""), 129, Null_Unbounded_String), (Comment, Null_Unbounded_String, Scan_Codes'Last, To_US (""Scan_Code_Locking_Caps_Lock : constant Scan_Codes := 130;"")), (Comment, Null_Unbounded_String, Scan_Codes'Last, To_US (""Scan_Code_Locking_Num_Lock : constant Scan_Codes := 131;"")), (Comment, Null_Unbounded_String, Scan_Codes'Last, To_US (""Scan_Code_Locking_Scroll_Lock : constant Scan_Codes := 132;"")), (Output, To_US (""Scan_Code_KP_Comma""), 133, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Equals_AS400""), 134, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_International_1""), 135, To_US (""Used on Asian keyboards."")), (Output, To_US (""Scan_Code_International_2""), 136, Null_Unbounded_String), (Output, To_US (""Scan_Code_International_3""), 137, To_US (""Yen"")), (Output, To_US (""Scan_Code_International_4""), 138, Null_Unbounded_String), (Output, To_US (""Scan_Code_International_5""), 139, Null_Unbounded_String), (Output, To_US (""Scan_Code_International_6""), 140, Null_Unbounded_String), (Output, To_US (""Scan_Code_International_7""), 141, Null_Unbounded_String), (Output, To_US (""Scan_Code_International_8""), 142, Null_Unbounded_String), (Output, To_US (""Scan_Code_International_9""), 143, Null_Unbounded_String), (Output, To_US (""Scan_Code_Language_1""), 144, To_US (""Hangul/En"")), (Output, To_US (""Scan_Code_Language_2""), 145, To_US (""Hanja con"")), (Output, To_US (""Scan_Code_Language_3""), 146, To_US (""Katakana."")), (Output, To_US (""Scan_Code_Language_4""), 147, To_US (""Hiragana."")), (Output, To_US (""Scan_Code_Language_5""), 148, To_US (""Zenkaku/H"")), (Output, To_US (""Scan_Code_Language_6""), 149, To_US (""Reserved."")), (Output, To_US (""Scan_Code_Language_7""), 150, To_US (""Reserved."")), (Output, To_US (""Scan_Code_Language_8""), 151, To_US (""Reserved."")), (Output, To_US (""Scan_Code_Language_9""), 152, To_US (""Reserved."")), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Alt_Erase""), 153, To_US (""Erase-ease."")), (Output, To_US (""Scan_Code_Sys_Req""), 154, Null_Unbounded_String), (Output, To_US (""Scan_Code_Cancel""), 155, Null_Unbounded_String), (Output, To_US (""Scan_Code_Clear""), 156, Null_Unbounded_String), (Output, To_US (""Scan_Code_Prior""), 157, Null_Unbounded_String), (Output, To_US (""Scan_Code_Return_2""), 158, Null_Unbounded_String), (Output, To_US (""Scan_Code_Separator""), 159, Null_Unbounded_String), (Output, To_US (""Scan_Code_Out""), 160, Null_Unbounded_String), (Output, To_US (""Scan_Code_Oper""), 161, Null_Unbounded_String), (Output, To_US (""Scan_Code_Clear_Again""), 162, Null_Unbounded_String), (Output, To_US (""Scan_Code_CR_Sel""), 163, Null_Unbounded_String), (Output, To_US (""Scan_Code_EX_Sel""), 164, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_KP_00""), 176, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_000""), 177, Null_Unbounded_String), (Output, To_US (""Scan_Code_Thousands_Separator""), 178, Null_Unbounded_String), (Output, To_US (""Scan_Code_Decimal_Separator""), 179, Null_Unbounded_String), (Output, To_US (""Scan_Code_Currency_Unit""), 180, Null_Unbounded_String), (Output, To_US (""Scan_Code_Currency_Subunit""), 181, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Left_Parenthesis""), 182, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Right_Parentheesis""), 183, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Left_Brace""), 184, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Right_Brace""), 185, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Tab""), 186, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Backspace""), 187, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_A""), 188, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_B""), 189, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_C""), 190, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_D""), 191, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_E""), 192, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_F""), 193, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_XOR""), 194, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Power""), 195, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Percent""), 196, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Less""), 197, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Greater""), 198, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Ampersand""), 199, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Double_Ampersand""), 200, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Vertical_Bar""), 201, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Double_Vertical_Bar""), 202, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Colon""), 203, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Hash""), 204, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Space""), 205, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_At""), 206, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Exclamation""), 207, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Memory_Store""), 208, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Memory_Recall""), 209, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Memory_Clear""), 210, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Memory_Add""), 211, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Memory_Subtract""), 212, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Memory_Multiply""), 213, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Memory_Divide""), 214, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Plus_Minus""), 215, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Clear""), 216, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Clear_Entry""), 217, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Binary""), 218, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Octal""), 219, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Decimal""), 220, Null_Unbounded_String), (Output, To_US (""Scan_Code_KP_Hexadecimal""), 221, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Left_Control""), 224, Null_Unbounded_String), (Output, To_US (""Scan_Code_Left_Shift""), 225, Null_Unbounded_String), (Output, To_US (""Scan_Code_Left_Alt""), 226, To_US (""Alt, option, etc."")), (Output, To_US (""Scan_Code_Left_GUI""), 227, To_US (""Windows, Command (Apple), Meta, etc."")), (Output, To_US (""Scan_Code_Right_Control""), 228, Null_Unbounded_String), (Output, To_US (""Scan_Code_Right_Shift""), 229, Null_Unbounded_String), (Output, To_US (""Scan_Code_Right_Alt""), 230, To_US (""Alt gr, option, etc."")), (Output, To_US (""Scan_Code_Right_GUI""), 231, To_US (""Windows, Command (Apple), Meta, etc."")), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Mode""), 257, Null_Unbounded_String), (New_Line_Scan_Code), (Comment, Null_Unbounded_String, Scan_Codes'Last, To_US (""Usage page in USB document."")), (Output, To_US (""Scan_Code_Audio_Next""), 258, Null_Unbounded_String), (Output, To_US (""Scan_Code_Audio_Previous""), 259, Null_Unbounded_String), (Output, To_US (""Scan_Code_Audio_Stop""), 260, Null_Unbounded_String), (Output, To_US (""Scan_Code_Audio_Play""), 261, Null_Unbounded_String), (Output, To_US (""Scan_Code_Audio_Mute""), 262, Null_Unbounded_String), (Output, To_US (""Scan_Code_Media_Select""), 263, Null_Unbounded_String), (Output, To_US (""Scan_Code_WWW""), 264, Null_Unbounded_String), (Output, To_US (""Scan_Code_Mail""), 265, Null_Unbounded_String), (Output, To_US (""Scan_Code_Calculator""), 266, Null_Unbounded_String), (Output, To_US (""Scan_Code_Computer""), 267, Null_Unbounded_String), (Output, To_US (""Scan_Code_AC_Search""), 268, Null_Unbounded_String), (Output, To_US (""Scan_Code_AC_Home""), 269, Null_Unbounded_String), (Output, To_US (""Scan_Code_AC_Back""), 270, Null_Unbounded_String), (Output, To_US (""Scan_Code_AC_Forward""), 271, Null_Unbounded_String), (Output, To_US (""Scan_Code_AC_Stop""), 272, Null_Unbounded_String), (Output, To_US (""Scan_Code_AC_Refresh""), 273, Null_Unbounded_String), (Output, To_US (""Scan_Code_AC_Bookmarks""), 274, Null_Unbounded_String), (New_Line_Scan_Code), (Comment, Null_Unbounded_String, Scan_Codes'Last, To_US (""Walther keys (for Mac?)."")), (Output, To_US (""Scan_Code_Brightness_Up""), 275, Null_Unbounded_String), (Output, To_US (""Scan_Code_Brightness_Down""), 276, Null_Unbounded_String), (Output, To_US (""Scan_Code_Display_Switch""), 277, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Illumination_Toggle""), 278, Null_Unbounded_String), (Output, To_US (""Scan_Code_Illumination_Down""), 279, Null_Unbounded_String), (Output, To_US (""Scan_Code_Illumination_Up""), 280, Null_Unbounded_String), (Output, To_US (""Scan_Code_Eject""), 281, Null_Unbounded_String), (Output, To_US (""Scan_Code_Sleep""), 282, Null_Unbounded_String), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Application_1""), 283, Null_Unbounded_String), (Output, To_US (""Scan_Code_Application_2""), 284, Null_Unbounded_String), (New_Line_Scan_Code), (Comment, Null_Unbounded_String, Scan_Codes'Last, To_US (""All other scan codes go here."")), (New_Line_Scan_Code), (Output, To_US (""Scan_Code_Total""), 512, Null_Unbounded_String)); -- See SDL_SCANCODE_TO_KEYCODE in include/SDL_keycode.h type Key_Codes is mod 2 ** 32 with Convention => C, Size => 32; Internal_To_Key_Code_Mask : constant Key_Codes := 16#4000_0000#; package Key_Codes_IO is new Modular_IO (Key_Codes); use Key_Codes_IO; function Convert is new Ada.Unchecked_Conversion (Source => Scan_Codes, Target => Key_Codes); function To_Key_Code (Code : in Scan_Codes) return Key_Codes is (Internal_To_Key_Code_Mask or Convert (Code)); type Key_Code_Mapping is record State : Mapping_States := Output; Name : Unbounded_String := Null_Unbounded_String; Code : Key_Codes := Key_Codes'Last; end record; New_Line_Code : constant Key_Code_Mapping := (New_Line, Null_Unbounded_String, Key_Codes'Last); type Key_Code_Tables is array (Positive range <>) of Key_Code_Mapping; Key_Code_Table : constant Key_Code_Tables := ((Output, To_US (""Code_Return""), Character'Pos (Latin_1.CR)), (Output, To_US (""Code_Escape""), Character'Pos (Latin_1.ESC)), (Output, To_US (""Code_Backspace""), Character'Pos (Latin_1.BS)), (Output, To_US (""Code_Tab""), Character'Pos (Latin_1.HT)), (Output, To_US (""Code_Space""), Character'Pos (Latin_1.Space)), (Output, To_US (""Code_Exclamation""), Character'Pos (Latin_1.Exclamation)), (Output, To_US (""Code_Double_Quote""), Character'Pos (Latin_1.Quotation)), (Output, To_US (""Code_Hash""), Character'Pos (Latin_1.Number_Sign)), (Output, To_US (""Code_Percent""), Character'Pos (Latin_1.Percent_Sign)), (Output, To_US (""Code_Dollar""), Character'Pos (Latin_1.Dollar_Sign)), (Output, To_US (""Code_Ampersand""), Character'Pos (Latin_1.Ampersand)), (Output, To_US (""Code_Quote""), Character'Pos (Latin_1.Apostrophe)), (Output, To_US (""Code_Left_Parenthesis""), Character'Pos (Latin_1.Left_Parenthesis)), (Output, To_US (""Code_Right_Parenthesis""), Character'Pos (Latin_1.Right_Parenthesis)), (Output, To_US (""Code_Asterisk""), Character'Pos (Latin_1.Asterisk)), (Output, To_US (""Code_Plus""), Character'Pos (Latin_1.Plus_Sign)), (Output, To_US (""Code_Comma""), Character'Pos (Latin_1.Comma)), (Output, To_US (""Code_Minus""), Character'Pos (Latin_1.Minus_Sign)), (Output, To_US (""Code_Period""), Character'Pos (Latin_1.Full_Stop)), (Output, To_US (""Code_Slash""), Character'Pos (Latin_1.Solidus)), (Output, To_US (""Code_0""), Character'Pos ('0')), (Output, To_US (""Code_1""), Character'Pos ('1')), (Output, To_US (""Code_2""), Character'Pos ('2')), (Output, To_US (""Code_3""), Character'Pos ('3')), (Output, To_US (""Code_4""), Character'Pos ('4')), (Output, To_US (""Code_5""), Character'Pos ('5')), (Output, To_US (""Code_6""), Character'Pos ('6')), (Output, To_US (""Code_7""), Character'Pos ('7')), (Output, To_US (""Code_8""), Character'Pos ('8')), (Output, To_US (""Code_9""), Character'Pos ('9')), (Output, To_US (""Code_Colon""), Character'Pos (Latin_1.Colon)), (Output, To_US (""Code_Semi_Colon""), Character'Pos (Latin_1.Semicolon)), (Output, To_US (""Code_Less""), Character'Pos (Latin_1.Less_Than_Sign)), (Output, To_US (""Code_Equals""), Character'Pos (Latin_1.Equals_Sign)), (Output, To_US (""Code_Greater""), Character'Pos (Latin_1.Greater_Than_Sign)), (Output, To_US (""Code_Question""), Character'Pos (Latin_1.Question)), (Output, To_US (""Code_At""), Character'Pos (Latin_1.Commercial_At)), (New_Line_Code), (Comment, To_US (""Skip the uppercase letters.""), Key_Codes'Last), (New_Line_Code), (Output, To_US (""Code_Left_Bracket""), Character'Pos (Latin_1.Left_Square_Bracket)), (Output, To_US (""Code_Back_Slash""), Character'Pos (Latin_1.Reverse_Solidus)), (Output, To_US (""Code_Right_Bracket""), Character'Pos (Latin_1.Right_Square_Bracket)), (Output, To_US (""Code_Caret""), Character'Pos (Latin_1.Circumflex)), (Output, To_US (""Code_Underscore""), Character'Pos (Latin_1.Low_Line)), (Output, To_US (""Code_Back_Quote""), Character'Pos (Latin_1.Grave)), (Output, To_US (""Code_A""), Character'Pos ('a')), (Output, To_US (""Code_B""), Character'Pos ('b')), (Output, To_US (""Code_C""), Character'Pos ('c')), (Output, To_US (""Code_D""), Character'Pos ('d')), (Output, To_US (""Code_E""), Character'Pos ('e')), (Output, To_US (""Code_F""), Character'Pos ('f')), (Output, To_US (""Code_G""), Character'Pos ('g')), (Output, To_US (""Code_H""), Character'Pos ('h')), (Output, To_US (""Code_I""), Character'Pos ('i')), (Output, To_US (""Code_J""), Character'Pos ('j')), (Output, To_US (""Code_K""), Character'Pos ('k')), (Output, To_US (""Code_L""), Character'Pos ('l')), (Output, To_US (""Code_M""), Character'Pos ('m')), (Output, To_US (""Code_N""), Character'Pos ('n')), (Output, To_US (""Code_O""), Character'Pos ('o')), (Output, To_US (""Code_P""), Character'Pos ('p')), (Output, To_US (""Code_Q""), Character'Pos ('q')), (Output, To_US (""Code_R""), Character'Pos ('r')), (Output, To_US (""Code_S""), Character'Pos ('s')), (Output, To_US (""Code_T""), Character'Pos ('t')), (Output, To_US (""Code_U""), Character'Pos ('u')), (Output, To_US (""Code_V""), Character'Pos ('v')), (Output, To_US (""Code_W""), Character'Pos ('w')), (Output, To_US (""Code_X""), Character'Pos ('x')), (Output, To_US (""Code_Y""), Character'Pos ('y')), (Output, To_US (""Code_Z""), Character'Pos ('z')), (New_Line_Code), (Output, To_US (""Code_Caps_Lock""), To_Key_Code (Scan_Code_Caps_Lock)), (Output, To_US (""Code_F1""), To_Key_Code (Scan_Code_F1)), (Output, To_US (""Code_F2""), To_Key_Code (Scan_Code_F2)), (Output, To_US (""Code_F3""), To_Key_Code (Scan_Code_F3)), (Output, To_US (""Code_F4""), To_Key_Code (Scan_Code_F4)), (Output, To_US (""Code_F5""), To_Key_Code (Scan_Code_F5)), (Output, To_US (""Code_F6""), To_Key_Code (Scan_Code_F6)), (Output, To_US (""Code_F7""), To_Key_Code (Scan_Code_F7)), (Output, To_US (""Code_F8""), To_Key_Code (Scan_Code_F8)), (Output, To_US (""Code_F9""), To_Key_Code (Scan_Code_F9)), (Output, To_US (""Code_F10""), To_Key_Code (Scan_Code_F10)), (Output, To_US (""Code_F11""), To_Key_Code (Scan_Code_F11)), (Output, To_US (""Code_F12""), To_Key_Code (Scan_Code_F12)), (New_Line_Code), (Output, To_US (""Code_Print_Screen""), To_Key_Code (Scan_Code_Print_Screen)), (Output, To_US (""Code_Scroll_Lock""), To_Key_Code (Scan_Code_Scroll_Lock)), (Output, To_US (""Code_Pause""), To_Key_Code (Scan_Code_Pause)), (Output, To_US (""Code_Insert""), To_Key_Code (Scan_Code_Insert)), (Output, To_US (""Code_Home""), To_Key_Code (Scan_Code_Home)), (Output, To_US (""Code_Page_Up""), To_Key_Code (Scan_Code_Page_Up)), (Output, To_US (""Code_Delete""), Character'Pos (Latin_1.DEL)), (Output, To_US (""Code_End""), To_Key_Code (Scan_Code_End)), (Output, To_US (""Code_Page_Down""), To_Key_Code (Scan_Code_Page_Down)), (Output, To_US (""Code_Right""), To_Key_Code (Scan_Code_Right)), (Output, To_US (""Code_Left""), To_Key_Code (Scan_Code_Left)), (Output, To_US (""Code_Down""), To_Key_Code (Scan_Code_Down)), (Output, To_US (""Code_Up""), To_Key_Code (Scan_Code_Up)), (New_Line_Code), (Output, To_US (""Code_Num_Lock_Clear""), To_Key_Code (Scan_Code_Num_Lock_Clear)), (Output, To_US (""Code_KP_Divide""), To_Key_Code (Scan_Code_KP_Divide)), (Output, To_US (""Code_KP_Multiply""), To_Key_Code (Scan_Code_KP_Multiply)), (Output, To_US (""Code_KP_Minus""), To_Key_Code (Scan_Code_KP_Minus)), (Output, To_US (""Code_KP_Plus""), To_Key_Code (Scan_Code_KP_Plus)), (Output, To_US (""Code_KP_Enter""), To_Key_Code (Scan_Code_KP_Enter)), (Output, To_US (""Code_KP_1""), To_Key_Code (Scan_Code_KP_1)), (Output, To_US (""Code_KP_2""), To_Key_Code (Scan_Code_KP_2)), (Output, To_US (""Code_KP_3""), To_Key_Code (Scan_Code_KP_3)), (Output, To_US (""Code_KP_4""), To_Key_Code (Scan_Code_KP_4)), (Output, To_US (""Code_KP_5""), To_Key_Code (Scan_Code_KP_5)), (Output, To_US (""Code_KP_6""), To_Key_Code (Scan_Code_KP_6)), (Output, To_US (""Code_KP_7""), To_Key_Code (Scan_Code_KP_7)), (Output, To_US (""Code_KP_8""), To_Key_Code (Scan_Code_KP_8)), (Output, To_US (""Code_KP_9""), To_Key_Code (Scan_Code_KP_9)), (Output, To_US (""Code_KP_0""), To_Key_Code (Scan_Code_KP_0)), (Output, To_US (""Code_KP_Period""), To_Key_Code (Scan_Code_KP_Period)), (New_Line_Code), (Output, To_US (""Code_Application""), To_Key_Code (Scan_Code_Application)), (Output, To_US (""Code_Power""), To_Key_Code (Scan_Code_Power)), (Output, To_US (""Code_KP_Equals""), To_Key_Code (Scan_Code_KP_Equals)), (Output, To_US (""Code_F13""), To_Key_Code (Scan_Code_F13)), (Output, To_US (""Code_F14""), To_Key_Code (Scan_Code_F14)), (Output, To_US (""Code_F15""), To_Key_Code (Scan_Code_F15)), (Output, To_US (""Code_F16""), To_Key_Code (Scan_Code_F16)), (Output, To_US (""Code_F17""), To_Key_Code (Scan_Code_F17)), (Output, To_US (""Code_F18""), To_Key_Code (Scan_Code_F18)), (Output, To_US (""Code_F19""), To_Key_Code (Scan_Code_F19)), (Output, To_US (""Code_F20""), To_Key_Code (Scan_Code_F20)), (Output, To_US (""Code_F21""), To_Key_Code (Scan_Code_F21)), (Output, To_US (""Code_F22""), To_Key_Code (Scan_Code_F22)), (Output, To_US (""Code_F23""), To_Key_Code (Scan_Code_F23)), (Output, To_US (""Code_F24""), To_Key_Code (Scan_Code_F24)), (Output, To_US (""Code_Execute""), To_Key_Code (Scan_Code_Execute)), (Output, To_US (""Code_Help""), To_Key_Code (Scan_Code_Help)), (Output, To_US (""Code_Menu""), To_Key_Code (Scan_Code_Menu)), (Output, To_US (""Code_Select""), To_Key_Code (Scan_Code_Select)), (Output, To_US (""Code_Stop""), To_Key_Code (Scan_Code_Stop)), (Output, To_US (""Code_Again""), To_Key_Code (Scan_Code_Again)), (Output, To_US (""Code_Undo""), To_Key_Code (Scan_Code_Undo)), (Output, To_US (""Code_Cut""), To_Key_Code (Scan_Code_Cut)), (Output, To_US (""Code_Copy""), To_Key_Code (Scan_Code_Copy)), (Output, To_US (""Code_Paste""), To_Key_Code (Scan_Code_Paste)), (Output, To_US (""Code_Find""), To_Key_Code (Scan_Code_Find)), (Output, To_US (""Code_Mute""), To_Key_Code (Scan_Code_Mute)), (Output, To_US (""Code_Volume_Up""), To_Key_Code (Scan_Code_Volume_Up)), (Output, To_US (""Code_Volume_Down""), To_Key_Code (Scan_Code_Volume_Down)), (Output, To_US (""Code_KP_Comma""), To_Key_Code (Scan_Code_KP_Comma)), (Output, To_US (""Code_KP_Equals_AS400""), To_Key_Code (Scan_Code_KP_Equals_AS400)), (New_Line_Code), (Output, To_US (""Code_Alt_Erase""), To_Key_Code (Scan_Code_Alt_Erase)), (Output, To_US (""Code_Sys_Req""), To_Key_Code (Scan_Code_Sys_Req)), (Output, To_US (""Code_Cancel""), To_Key_Code (Scan_Code_Cancel)), (Output, To_US (""Code_Clear""), To_Key_Code (Scan_Code_Clear)), (Output, To_US (""Code_Prior""), To_Key_Code (Scan_Code_Prior)), (Output, To_US (""Code_Return_2""), To_Key_Code (Scan_Code_Return_2)), (Output, To_US (""Code_Separator""), To_Key_Code (Scan_Code_Separator)), (Output, To_US (""Code_Out""), To_Key_Code (Scan_Code_Out)), (Output, To_US (""Code_Oper""), To_Key_Code (Scan_Code_Oper)), (Output, To_US (""Code_Clear_Again""), To_Key_Code (Scan_Code_Clear_Again)), (Output, To_US (""Code_CR_Sel""), To_Key_Code (Scan_Code_CR_Sel)), (Output, To_US (""Code_Ex_Sel""), To_Key_Code (Scan_Code_EX_Sel)), (New_Line_Code), (Output, To_US (""Code_KP_00""), To_Key_Code (Scan_Code_KP_00)), (Output, To_US (""Code_KP_000""), To_Key_Code (Scan_Code_KP_000)), (Output, To_US (""Code_Thousands_Separator""), To_Key_Code (Scan_Code_Thousands_Separator)), (Output, To_US (""Code_Decimal_Separator""), To_Key_Code (Scan_Code_Decimal_Separator)), (Output, To_US (""Code_Currency_Unit""), To_Key_Code (Scan_Code_Currency_Unit)), (Output, To_US (""Code_Currency_Subunit""), To_Key_Code (Scan_Code_Currency_Subunit)), (Output, To_US (""Code_KP_Left_Parenthesis""), To_Key_Code (Scan_Code_KP_Left_Parenthesis)), (Output, To_US (""Code_KP_Right_Parentheesis""), To_Key_Code (Scan_Code_KP_Right_Parentheesis)), (Output, To_US (""Code_KP_Left_Brace""), To_Key_Code (Scan_Code_KP_Left_Brace)), (Output, To_US (""Code_KP_Right_Brace""), To_Key_Code (Scan_Code_KP_Right_Brace)), (Output, To_US (""Code_KP_Tab""), To_Key_Code (Scan_Code_KP_Tab)), (Output, To_US (""Code_KP_Backspace""), To_Key_Code (Scan_Code_KP_Backspace)), (Output, To_US (""Code_KP_A""), To_Key_Code (Scan_Code_KP_A)), (Output, To_US (""Code_KP_B""), To_Key_Code (Scan_Code_KP_B)), (Output, To_US (""Code_KP_C""), To_Key_Code (Scan_Code_KP_C)), (Output, To_US (""Code_KP_D""), To_Key_Code (Scan_Code_KP_D)), (Output, To_US (""Code_KP_E""), To_Key_Code (Scan_Code_KP_E)), (Output, To_US (""Code_KP_F""), To_Key_Code (Scan_Code_KP_F)), (Output, To_US (""Code_KP_XOR""), To_Key_Code (Scan_Code_KP_XOR)), (Output, To_US (""Code_KP_Power""), To_Key_Code (Scan_Code_KP_Power)), (Output, To_US (""Code_KP_Percent""), To_Key_Code (Scan_Code_KP_Percent)), (Output, To_US (""Code_KP_Less""), To_Key_Code (Scan_Code_KP_Less)), (Output, To_US (""Code_KP_Greater""), To_Key_Code (Scan_Code_KP_Greater)), (Output, To_US (""Code_KP_Ampersand""), To_Key_Code (Scan_Code_KP_Ampersand)), (Output, To_US (""Code_KP_Double_Ampersand""), To_Key_Code (Scan_Code_KP_Double_Ampersand)), (Output, To_US (""Code_KP_Vertical_Bar""), To_Key_Code (Scan_Code_KP_Vertical_Bar)), (Output, To_US (""Code_KP_Double_Vertical_Bar""), To_Key_Code (Scan_Code_KP_Double_Vertical_Bar)), (Output, To_US (""Code_KP_Colon""), To_Key_Code (Scan_Code_KP_Colon)), (Output, To_US (""Code_KP_Hash""), To_Key_Code (Scan_Code_KP_Hash)), (Output, To_US (""Code_KP_Space""), To_Key_Code (Scan_Code_KP_Space)), (Output, To_US (""Code_KP_At""), To_Key_Code (Scan_Code_KP_At)), (Output, To_US (""Code_KP_Exclamation""), To_Key_Code (Scan_Code_KP_Exclamation)), (Output, To_US (""Code_KP_Memory_Store""), To_Key_Code (Scan_Code_KP_Memory_Store)), (Output, To_US (""Code_KP_Memory_Recall""), To_Key_Code (Scan_Code_KP_Memory_Recall)), (Output, To_US (""Code_KP_Memory_Clear""), To_Key_Code (Scan_Code_KP_Memory_Clear)), (Output, To_US (""Code_KP_Memory_Add""), To_Key_Code (Scan_Code_KP_Memory_Add)), (Output, To_US (""Code_KP_Memory_Subtract""), To_Key_Code (Scan_Code_KP_Memory_Subtract)), (Output, To_US (""Code_KP_Memory_Multiply""), To_Key_Code (Scan_Code_KP_Memory_Multiply)), (Output, To_US (""Code_KP_Memory_Divide""), To_Key_Code (Scan_Code_KP_Memory_Divide)), (Output, To_US (""Code_KP_Plus_Minus""), To_Key_Code (Scan_Code_KP_Plus_Minus)), (Output, To_US (""Code_KP_Clear""), To_Key_Code (Scan_Code_KP_Clear)), (Output, To_US (""Code_KP_Clear_Entry""), To_Key_Code (Scan_Code_KP_Clear_Entry)), (Output, To_US (""Code_KP_Binary""), To_Key_Code (Scan_Code_KP_Binary)), (Output, To_US (""Code_KP_Octal""), To_Key_Code (Scan_Code_KP_Octal)), (Output, To_US (""Code_KP_Decimal""), To_Key_Code (Scan_Code_KP_Decimal)), (Output, To_US (""Code_KP_Hexadecimal""), To_Key_Code (Scan_Code_KP_Hexadecimal)), (New_Line_Code), (Output, To_US (""Code_Left_Control""), To_Key_Code (Scan_Code_Left_Control)), (Output, To_US (""Code_Left_Shift""), To_Key_Code (Scan_Code_Left_Shift)), (Output, To_US (""Code_Left_Alt""), To_Key_Code (Scan_Code_Left_Alt)), (Output, To_US (""Code_Left_GUI""), To_Key_Code (Scan_Code_Left_GUI)), (Output, To_US (""Code_Right_Control""), To_Key_Code (Scan_Code_Right_Control)), (Output, To_US (""Code_Right_Shift""), To_Key_Code (Scan_Code_Right_Shift)), (Output, To_US (""Code_Right_Alt""), To_Key_Code (Scan_Code_Right_Alt)), (Output, To_US (""Code_Right_GUI""), To_Key_Code (Scan_Code_Right_GUI)), (New_Line_Code), (Output, To_US (""Code_Mode""), To_Key_Code (Scan_Code_Mode)), (New_Line_Code), (Output, To_US (""Code_Audio_Next""), To_Key_Code (Scan_Code_Audio_Next)), (Output, To_US (""Code_Audio_Previous""), To_Key_Code (Scan_Code_Audio_Previous)), (Output, To_US (""Code_Audio_Stop""), To_Key_Code (Scan_Code_Audio_Stop)), (Output, To_US (""Code_Audio_Play""), To_Key_Code (Scan_Code_Audio_Play)), (Output, To_US (""Code_Audio_Mute""), To_Key_Code (Scan_Code_Audio_Mute)), (Output, To_US (""Code_Media_Select""), To_Key_Code (Scan_Code_Media_Select)), (Output, To_US (""Code_WWW""), To_Key_Code (Scan_Code_WWW)), (Output, To_US (""Code_Mail""), To_Key_Code (Scan_Code_Mail)), (Output, To_US (""Code_Calculator""), To_Key_Code (Scan_Code_Calculator)), (Output, To_US (""Code_Computer""), To_Key_Code (Scan_Code_Computer)), (Output, To_US (""Code_AC_Search""), To_Key_Code (Scan_Code_AC_Search)), (Output, To_US (""Code_AC_Home""), To_Key_Code (Scan_Code_AC_Home)), (Output, To_US (""Code_AC_Back""), To_Key_Code (Scan_Code_AC_Back)), (Output, To_US (""Code_AC_Forward""), To_Key_Code (Scan_Code_AC_Forward)), (Output, To_US (""Code_AC_Stop""), To_Key_Code (Scan_Code_AC_Stop)), (Output, To_US (""Code_AC_Refresh""), To_Key_Code (Scan_Code_AC_Refresh)), (Output, To_US (""Code_AC_Bookmarks""), To_Key_Code (Scan_Code_AC_Bookmarks)), (New_Line_Code), (Output, To_US (""Code_Brightness_Down""), To_Key_Code (Scan_Code_Brightness_Down)), (Output, To_US (""Code_Brightness_Up""), To_Key_Code (Scan_Code_Brightness_Up)), (Output, To_US (""Code_Display_Switch""), To_Key_Code (Scan_Code_Display_Switch)), (Output, To_US (""Code_Illumination_Toggle""), To_Key_Code (Scan_Code_Illumination_Toggle)), (Output, To_US (""Code_Illumination_Down""), To_Key_Code (Scan_Code_Illumination_Down)), (Output, To_US (""Code_Illumination_Up""), To_Key_Code (Scan_Code_Illumination_Up)), (Output, To_US (""Code_Eject""), To_Key_Code (Scan_Code_Eject)), (Output, To_US (""Code_Sleep""), To_Key_Code (Scan_Code_Sleep))); begin Comment (Indent => 0, Text => ""Automatically generated, do not edit.""); Comment_Dash (117); for Line of License loop Comment (Indent => 0, Text => To_String (Line)); end loop; Comment_Dash (117); for Line of Package_Description loop Comment (Indent => 0, Text => To_String (Line)); end loop; Comment_Dash (117); Put_Line (""with SDL.Video.Windows;""); New_Line; Put_Line (""package SDL.Events.Keyboards is""); Put_Line ("" pragma Preelaborate;""); Put_Line ("" -- Keyboard events.""); Put_Line ("" Key_Down : constant Event_Types := 16#0000_0300#;""); Put_Line ("" Key_Up : constant Event_Types := Key_Down + 1;""); Put_Line ("" Text_Editing : constant Event_Types := Key_Down + 2;""); Put_Line ("" Text_Input : constant Event_Types := Key_Down + 3;""); New_Line; -- Output the scan codes. Comment_Dash (Total => 114, Indent => 3); Put_Line ("" -- Scan codes.""); Comment_Dash (Total => 114, Indent => 3); Put_Line ("" type Scan_Codes is range 0 .. 512 with""); Put_Line ("" Convention => C,""); Put_Line ("" Size => 32;""); New_Line; for Code of Scan_Code_Table loop case Code.State is when Output => Output_Field (Text => To_String (Code.Name), Width => 33, Indent => 3); Put ("": constant Scan_Codes := ""); Put (Code.Code, Width => 0); Put (Latin_1.Semicolon); if Code.Comment /= Null_Unbounded_String then Put ("" -- "" & To_String (Code.Comment)); end if; New_Line; when New_Line => New_Line; when Comment => Comment (Indent => 3, Text => To_String (Code.Comment)); end case; end loop; New_Line; Put_Line ("" function Value (Name : in String) return SDL.Events.Keyboards.Scan_Codes with""); Put_Line ("" Inline => True;""); New_Line; Put_Line ("" function Image (Scan_Code : in SDL.Events.Keyboards.Scan_Codes) return String with""); Put_Line ("" Inline => True;""); New_Line; Comment_Dash (Total => 114, Indent => 3); Comment (Indent => 3, Text => ""Key codes.""); Comment_Dash (Total => 114, Indent => 3); Put_Line ("" type Key_Codes is mod 2 ** 32 with""); Put_Line ("" Convention => C,""); Put_Line ("" Size => 32;""); New_Line; for Code of Key_Code_Table loop case Code.State is when Output => Output_Field (Text => To_String (Code.Name), Width => 33, Indent => 3); Put ("": constant Key_Codes := ""); Put (Code.Code, Width => 12, Base => 16); Put (Latin_1.Semicolon); New_Line; when New_Line => New_Line; when Comment => Comment (Indent => 3, Text => To_String (Code.Name)); end case; end loop; New_Line; Put_Line ("" function Value (Name : in String) return SDL.Events.Keyboards.Key_Codes with""); Put_Line ("" Inline => True;""); New_Line; Put_Line ("" function Image (Key_Code : in SDL.Events.Keyboards.Key_Codes) return String with""); Put_Line ("" Inline => True;""); New_Line; Put_Line ("" function To_Key_Code (Scan_Code : in SDL.Events.Keyboards.Scan_Codes) return "" & ""SDL.Events.Keyboards.Key_Codes with""); Put_Line ("" Inline => True;""); New_Line; Put_Line ("" function To_Scan_Code (Key_Code : in SDL.Events.Keyboards.Key_Codes) return "" & ""SDL.Events.Keyboards.Scan_Codes with""); Put_Line ("" Inline => True;""); New_Line; Comment_Dash (Total => 114, Indent => 3); Comment (Indent => 3, Text => ""Key modifiers.""); Comment_Dash (Total => 114, Indent => 3); Put_Line ("" type Key_Modifiers is mod 2 ** 16 with""); Put_Line ("" Convention => C,""); Put_Line ("" Size => 16;""); New_Line; Put_Line ("" Modifier_None : constant Key_Modifiers := 16#00_00#;""); Put_Line ("" Modifier_Left_Shift : constant Key_Modifiers := 16#00_01#;""); Put_Line ("" Modifier_Right_Shift : constant Key_Modifiers := 16#00_02#;""); Put_Line ("" Modifier_Left_Control : constant Key_Modifiers := 16#00_40#;""); Put_Line ("" Modifier_Right_Control : constant Key_Modifiers := 16#00_80#;""); Put_Line ("" Modifier_Left_Alt : constant Key_Modifiers := 16#01_00#;""); Put_Line ("" Modifier_Right_Alt : constant Key_Modifiers := 16#02_00#;""); Put_Line ("" Modifier_Left_GUI : constant Key_Modifiers := 16#04_00#;""); Put_Line ("" Modifier_Right_GUI : constant Key_Modifiers := 16#08_00#;""); Put_Line ("" Modifier_Num : constant Key_Modifiers := 16#10_00#;""); Put_Line ("" Modifier_Caps : constant Key_Modifiers := 16#20_00#;""); Put_Line ("" Modifier_Mode : constant Key_Modifiers := 16#40_00#;""); Put_Line ("" Modifier_Control : constant Key_Modifiers := Modifier_Left_Control or Modifier_Right_Control;""); Put_Line ("" Modifier_Shift : constant Key_Modifiers := Modifier_Left_Shift or Modifier_Right_Shift;""); Put_Line ("" Modifier_Alt : constant Key_Modifiers := Modifier_Left_Alt or Modifier_Right_Alt;""); Put_Line ("" Modifier_GUI : constant Key_Modifiers := Modifier_Left_GUI or Modifier_Right_GUI;""); Put_Line ("" Modifier_Reserved : constant Key_Modifiers := 16#80_00#;""); New_Line; Put_Line ("" type Key_Syms is""); Put_Line ("" record""); Put_Line ("" Scan_Code : Scan_Codes;""); Put_Line ("" Key_Code : Key_Codes;""); Put_Line ("" Modifiers : Key_Modifiers;""); Put_Line ("" Unused : Interfaces.Unsigned_32;""); Put_Line ("" end record with""); Put_Line ("" Convention => C;""); New_Line; Put_Line ("" type Keyboard_Events is""); Put_Line ("" record""); Put_Line ("" Event_Type : Event_Types; -- Will be set to Key_Up/Down.""); Put_Line ("" Time_Stamp : Time_Stamps;""); New_Line; Put_Line ("" ID : SDL.Video.Windows.ID;""); Put_Line ("" State : Button_State;""); Put_Line ("" Repeat : Interfaces.Unsigned_8;""); Put_Line ("" Padding_2 : Padding_8;""); Put_Line ("" Padding_3 : Padding_8;""); Put_Line ("" Key_Sym : Key_Syms;""); Put_Line ("" end record with""); Put_Line ("" Convention => C;""); New_Line; Comment_Dash (Total => 114, Indent => 3); Comment (Indent => 3, Text => ""Text editing events.""); Comment_Dash (Total => 114, Indent => 3); Put_Line ("" Max_UTF8_Elements : constant := 31;""); Put_Line ("" Max_UTF8_Element_Storage_Bits : constant := ((Max_UTF8_Elements + 1) * 8) - 1;""); New_Line; Put_Line ("" subtype UTF8_Text_Buffers is Interfaces.C.char_array (0 .. Max_UTF8_Elements);""); New_Line; Put_Line ("" type Cursor_Positions is range -2 ** 31 .. 2 ** 31 - 1 with""); Put_Line ("" Convention => C,""); Put_Line ("" Size => 32;""); New_Line; Put_Line ("" type Text_Lengths is range -2 ** 31 .. 2 ** 31 - 1 with""); Put_Line ("" Convention => C,""); Put_Line ("" Size => 32;""); New_Line; Put_Line ("" type Text_Editing_Events is""); Put_Line ("" record""); Put_Line ("" Event_Type : Event_Types; -- Will be set to Text_Editing.""); Put_Line ("" Time_Stamp : Time_Stamps;""); New_Line; Put_Line ("" ID : SDL.Video.Windows.ID;""); Put_Line ("" Text : UTF8_Text_Buffers;""); Put_Line ("" Start : Cursor_Positions; -- TODO: Find out why this needs to be a signed value!""); Put_Line ("" Length : Text_Lengths; -- TODO: Again, signed, why?""); Put_Line ("" end record with""); Put_Line ("" Convention => C;""); New_Line; Comment_Dash (Total => 114, Indent => 3); Comment (Indent => 3, Text => ""Text input events.""); Comment_Dash (Total => 114, Indent => 3); Put_Line ("" type Text_Input_Events is""); Put_Line ("" record""); Put_Line ("" Event_Type : Event_Types; -- Will be set to Text_Editing.""); Put_Line ("" Time_Stamp : Time_Stamps;""); New_Line; Put_Line ("" ID : SDL.Video.Windows.ID;""); Put_Line ("" Text : UTF8_Text_Buffers;""); Put_Line ("" end record with""); Put_Line ("" Convention => C;""); New_Line; Put_Line (""private""); Put_Line ("" for Key_Syms use""); Put_Line ("" record""); Put_Line ("" Scan_Code at 0 * SDL.Word range 0 .. 31;""); Put_Line ("" Key_Code at 1 * SDL.Word range 0 .. 31;""); Put_Line ("" Modifiers at 2 * SDL.Word range 0 .. 15;""); Put_Line ("" Unused at 3 * SDL.Word range 0 .. 31;""); Put_Line ("" end record;""); New_Line; Put_Line ("" for Keyboard_Events use""); Put_Line ("" record""); Put_Line ("" Event_Type at 0 * SDL.Word range 0 .. 31;""); Put_Line ("" Time_Stamp at 1 * SDL.Word range 0 .. 31;""); New_Line; Put_Line ("" ID at 2 * SDL.Word range 0 .. 31;""); Put_Line ("" State at 3 * SDL.Word range 0 .. 7;""); Put_Line ("" Repeat at 3 * SDL.Word range 8 .. 15;""); Put_Line ("" Padding_2 at 3 * SDL.Word range 16 .. 23;""); Put_Line ("" Padding_3 at 3 * SDL.Word range 24 .. 31;""); Put_Line ("" end record;""); New_Line; Put_Line ("" for Text_Editing_Events use""); Put_Line ("" record""); Put_Line ("" Event_Type at 0 * SDL.Word range 0 .. 31;""); Put_Line ("" Time_Stamp at 1 * SDL.Word range 0 .. 31;""); New_Line; Put_Line ("" ID at 2 * SDL.Word range 0 .. 31;""); Put_Line ("" Text at 3 * SDL.Word range 0 .. Max_UTF8_Element_Storage_Bits; -- 31 characters.""); Put_Line ("" Start at 11 * SDL.Word range 0 .. 31;""); Put_Line ("" Length at 12 * SDL.Word range 0 .. 31;""); Put_Line ("" end record;""); New_Line; Put_Line ("" for Text_Input_Events use""); Put_Line ("" record""); Put_Line ("" Event_Type at 0 * SDL.Word range 0 .. 31;""); Put_Line ("" Time_Stamp at 1 * SDL.Word range 0 .. 31;""); New_Line; Put_Line ("" ID at 2 * SDL.Word range 0 .. 31;""); Put_Line ("" Text at 3 * SDL.Word range 0 .. Max_UTF8_Element_Storage_Bits; -- 31 characters.""); Put_Line ("" end record;""); Put_Line (""end SDL.Events.Keyboards;""); end Gen_Keyboard; ",16165,True,3358.7447711325954,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// // TODO (chiedozi): TabbedViewNavigator should override setActive and activate // the correct ViewNavigator. package spark.components { import flash.display.Stage; import flash.events.Event; import flash.events.IEventDispatcher; import flash.events.MouseEvent; import mx.core.ISelectableList; import mx.core.IVisualElement; import mx.core.UIComponent; import mx.core.mx_internal; import mx.effects.IEffect; import mx.effects.Parallel; import mx.events.CollectionEvent; import mx.events.CollectionEventKind; import mx.events.EffectEvent; import mx.events.FlexEvent; import mx.events.PropertyChangeEvent; import mx.events.PropertyChangeEventKind; import mx.managers.LayoutManager; import mx.resources.ResourceManager; import spark.components.supportClasses.ButtonBarBase; import spark.components.supportClasses.ViewNavigatorBase; import spark.effects.Animate; import spark.effects.animation.MotionPath; import spark.effects.animation.SimpleMotionPath; import spark.events.ElementExistenceEvent; import spark.events.IndexChangeEvent; import spark.events.RendererExistenceEvent; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when the current view navigator changes as a result of * a change to the selectedIndex property or a change * to the selected tab in the TabBar control. * * @eventType spark.events.IndexChangeEvent.CHANGE * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""change"", type=""spark.events.IndexChangeEvent"")] /** * Dispatched before the selected view navigator is changed. * Canceling this event prevents the active view navigator * from changing. * * @eventType spark.events.IndexChangeEvent.CHANGING * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""changing"", type=""spark.events.IndexChangeEvent"")] /** * Dispatched when the collection of view navigators managed by the * TabbedViewNavigator changes. * * @eventType mx.events.CollectionEvent.COLLECTION_CHANGE * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""collectionChange"", type=""mx.events.CollectionEvent"")] /** * Dispatched when the view navigator's selected index changes. * When this event is dispatched, the selectedIndex * and selectedNavigator properties reference the * newly selected view navigator. * * @eventType mx.events.FlexEvent.VALUE_COMMIT * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""valueCommit"", type=""mx.events.FlexEvent"")] //-------------------------------------- // Other metadata //-------------------------------------- [IconFile(""TabbedViewNavigator.png"")] /** * The TabbedViewNavigator class is a container that manages a collection * of view navigator containers. * Only one view navigator is active and visible at a time. * This class includes a TabBar control that provides the ability to toggle between * the collection of view navigators. * *

The following image shows a TabbedViewNavigator with three sections: * Employees, Contacts, and Search:

* *

* *

* *

The TabbedViewNavigatorApplication container automatically creates * a single TabbedViewNavigator container for the entire application. * You can reference the TabbedViewNavigator object by using the navigator * property of the TabbedViewNavigatorApplication container.

* *

The active or selected navigator can be changed by clicking the corresponding * tab in the TabBar or by changing the selectedIndex property of * the component.

* *

The contents of a child view navigator is destroyed when it is deactivate, * and dynamically created when activated.

* * @see spark.components.View * @see spark.components.ViewNavigator * @see spark.components.TabBar * * @includeExample examples/TabbedViewNavigatorExample.mxml -noswf * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class TabbedViewNavigator extends ViewNavigatorBase implements ISelectableList { //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- // TODO (chiedozi): Consider having a NO_SELECTION constant to differentiate // between NO_PROPOSED_SELECTION and clearing the selection. See List. It // seems redundant because TabbedViewNavigator expects requireSelection to be // true on its TabBar. /** * @private * Static constant representing no proposed selection. */ private static const NO_PROPOSED_SELECTION:int = -1; /** * @private * The animation duration used when hiding and showing the action bar. */ private static const TAB_BAR_ANIMATION_DURATION:Number = 250; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function TabbedViewNavigator() { super(); addEventListener(ElementExistenceEvent.ELEMENT_ADD, elementAddHandler); addEventListener(ElementExistenceEvent.ELEMENT_REMOVE, elementRemoveHandler); } //-------------------------------------------------------------------------- // // Skin Parts // //-------------------------------------------------------------------------- [Bindable] [SkinPart(required=""false"")] /** * A skin part that defines the tab bar of the navigator. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public var tabBar:ButtonBarBase; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var animateTabBarVisbility:Boolean = false; /** * @private */ private var contentGroupProps:Object; /** * @private * Determines if a changing event has already been dispatched. * This was introduced to prevent the IndexChangeEvent from * dispatching twice when the tabBar selection changes. */ private var changingEventDispatched:Boolean = false; /** * @private */ private var dataProviderChanged:Boolean = false; /** * @private */ private var explicitTabBarMouseEnabled:Boolean = false; /** * @private * Keeps track of the tab that was last selected. See * tabBarRendererClicked() for information on how it's used. */ private var lastSelectedIndex:int = -1; /** * @private */ private var selectedIndexChanged:Boolean = false; /** * @private */ private var selectedIndexAdjusted:Boolean = false; /** * @private */ private var showingTabBar:Boolean; /** * @private */ private var tabBarVisibilityEffect:IEffect; /** * @private */ private var tabBarProps:Object; /** * @private */ private var tabBarVisibilityChanged:Boolean = false; /** * @private */ mx_internal var selectedNavigatorChangingView:Boolean = false; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // activeView //---------------------------------- [Bindable(""viewChangeComplete"")] /** * @private */ override public function get activeView():View { if (selectedNavigator) return selectedNavigator.activeView; return null; } //---------------------------------- // exitApplicationOnBackKey //---------------------------------- /** * @private */ override mx_internal function get exitApplicationOnBackKey():Boolean { if (selectedNavigator) return selectedNavigator.exitApplicationOnBackKey; return super.exitApplicationOnBackKey; } //---------------------------------- // maintainNavigationStack //---------------------------------- private var _maintainNavigationStack:Boolean = true; /** * @private * Specifies whether the navigation stack of the view navigator * should remain intact when the view navigator is deactivated. * If true, when reactivated the view history * remains the same. * If false, the navigator displays the * first view in its navigation stack. * * @default true * * @see spark.components.ViewNavigator * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function get maintainNavigationStack():Boolean { return _maintainNavigationStack; } /** * @private */ mx_internal function set maintainNavigationStack(value:Boolean):void { _maintainNavigationStack = value; } //---------------------------------- // navigators //---------------------------------- /** * The view navigators that are managed by this TabbedViewNavigator. * Each view navigator is represented as a tab in the tab bar * of this TabbedViewNavigator. * Only one view navigator can be active at a time. * You can reference the active view navigator by using * the selectedNavigator property. * *

Changing this property causes the current view navigator to be removed, * and sets the selectedIndex to 0. * This operation cannot be canceled and is committed immediately.

* * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get navigators():Vector. { var mxmlContent:Array = currentContentGroup.getMXMLContent(); if (!mxmlContent) return null; // When this class was first released, navigators was typed Vector // and not Array. In 4.6, TabbedViewNavigator moved away from this // model and uses mxmlContent to manage children. To maintain backwards // compatibility, the return type for this method remained the same. // As a result, the mxmlContent array will need to converted. return Vector.(mxmlContent); } /** * @private */ public function set navigators(value:Vector.):void { // When this class was first released, navigators was typed Vector // and not Array. In 4.6, TabbedViewNavigator moved away from this // model and uses mxmlContent to manage children. To maintain backwards // compatibility, the return type for this method remained the same. // As a result, the value vector needs to be converted to an array var contentArray:Array = []; for each (var navigator:ViewNavigatorBase in value) { contentArray.push(navigator); setupNavigator(navigator); } mxmlContent = contentArray; // The proposed selected index is reset because it is no longer valid // since the array of navigators has changed. selectedIndexChanged = false; // Invalidate property flags dataProviderChanged = true; invalidateProperties(); // Notify listeners that the collection changed internalDispatchEvent(CollectionEventKind.RESET); } //---------------------------------- // selectedNavigator //---------------------------------- [Bindable(""change"")] /** * The selected view navigator for the TabbedViewNavigator. * Only one view navigator can be active at a time. * The active view navigator can be set by changing the * selectedIndex property or by selecting * a tab in the TabBar control. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get selectedNavigator():ViewNavigatorBase { if (length == 0 || selectedIndex < 0 || selectedIndex >= length) return null; return getElementAt(selectedIndex) as ViewNavigatorBase; } //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- /** * Hides the tab bar of the navigator. * * @param animate Indicates whether a hide effect should play * as the tab bar disappears. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function hideTabBar(animate:Boolean = true):void { if (!tabBar) return; showingTabBar = false; animateTabBarVisbility = animate; tabBarVisibilityChanged = true; invalidateProperties(); } /** * Shows the tab bar of the navigator * * @param animate Indicates whether a show effect should play * as the tab bar appears. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function showTabBar(animate:Boolean = true):void { if (!tabBar) return; showingTabBar = true; animateTabBarVisbility = animate; tabBarVisibilityChanged = true; invalidateProperties(); } /** * @private * Updates the navigator's state based on the properties set * on the active view. The main use cases are to hide the * TabBar and the change the overlay state. * * @param view The active view. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ override public function updateControlsForView(view:View):void { super.updateControlsForView(view); if (view) { if (tabBar) tabBar.visible = tabBar.includeInLayout = view.tabBarVisible; overlayControls = view.overlayControls; } else { // If the current view is null, the tab bar is shown so that the // user still has a ui for changing the selected tab. if (tabBar) tabBar.visible = tabBar.includeInLayout = true; overlayControls = false; } tabBarVisibilityChanged = false; } /** * Calls the backKeyUpHandler() of the selected navigator. * *

TabbedViewNavigatorApplication automatically calls this method when * the back key is pressed.

* * @langversion 3.0 * @playerversion AIR 3.1 * @productversion Flex 4.6 */ override public function backKeyUpHandler():void { if (selectedNavigator) selectedNavigator.backKeyUpHandler(); } //-------------------------------------------------------------------------- // // Private Methods // //-------------------------------------------------------------------------- /** * @private * Calculates the final positions for the tab bar visibility animations. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function prepareTabBarForAnimation(showAnimation:Boolean):void { var animateTabBarUp:Boolean; if (overlayControls) { // If the control is overlaid on top, the tabBar is animated up if // the tabBar is above the center of the navigator animateTabBarUp = (tabBar.y + (tabBar.height / 2)) <= height / 2; } else { // The tabBar is animated up if it is above the contentGroup animateTabBarUp = tabBar.y <= contentGroup.y; } // Need to validate to capture final positions and sizes of skin parts LayoutManager.getInstance().validateNow(); // This will store the final location and sizes of the components tabBarProps.end = captureAnimationValues(tabBar); contentGroupProps.end = captureAnimationValues(contentGroup); if (tabBarVisibilityChanged) { if (animateTabBarUp) { if (tabBarProps.start.visible) tabBarProps.end.y = -tabBar.height; else tabBarProps.start.y = -tabBar.height; } else { if (tabBarProps.start.visible) tabBarProps.end.y = this.height; else tabBarProps.start.y = this.height; } } tabBar.visible = true; tabBar.includeInLayout = false; tabBar.cacheAsBitmap = true; } /** * @private */ override mx_internal function canRemoveCurrentView():Boolean { return (!selectedNavigator || selectedNavigator.canRemoveCurrentView()); } /** * @private */ private function addNavigatorListeners(navigator:ViewNavigatorBase):void { navigator.addEventListener(""viewChangeComplete"", navigator_viewChangeCompleteHandler); navigator.addEventListener(""viewChangeStart"", navigator_viewChangeStartHandler); navigator.addEventListener(ElementExistenceEvent.ELEMENT_ADD, navigator_elementAddHandler); navigator.addEventListener(ElementExistenceEvent.ELEMENT_REMOVE, navigator_elementRemoveHandler); } /** * @private */ private function removeNavigatorListeners(navigator:ViewNavigatorBase):void { navigator.removeEventListener(""viewChangeComplete"", navigator_viewChangeCompleteHandler); navigator.removeEventListener(""viewChangeStart"", navigator_viewChangeStartHandler); navigator.removeEventListener(ElementExistenceEvent.ELEMENT_ADD, navigator_elementAddHandler); navigator.removeEventListener(ElementExistenceEvent.ELEMENT_REMOVE, navigator_elementRemoveHandler); } /** * @private */ private function setupNavigator(navigator:ViewNavigatorBase):void { navigator.setParentNavigator(this); navigator.visible = false; navigator.includeInLayout = false; // All navigators should be inactive when initialized. The proper // navigator will be activated during commitProperties(). navigator.setActive(false); startTrackingUpdates(navigator); } /** * @private */ private function cleanUpNavigator(navigator:ViewNavigatorBase):void { navigator.setParentNavigator(null); if (navigator.isActive) navigator.setActive(false); if (navigator.activeView) { navigator.activeView.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } removeNavigatorListeners(navigator); stopTrackingUpdates(navigator); } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ override protected function commitProperties():void { var changeEvent:IndexChangeEvent; if (selectedIndexChanged || selectedIndexAdjusted || dataProviderChanged) { var navigator:ViewNavigatorBase; // Store the old index var oldIndex:int = _selectedIndex; if (selectedIndex >= length) selectedIndex = (length > 0) ? 0 : NO_PROPOSED_SELECTION; var indexChangedPrevented:Boolean = false; // The selected index property can be changed programmitically on the // TabbedViewNavigator or by its tab bar in response to a user action. If // this was initiated by the tab bar, a chaning event would have already been // dispatched in tabBar_indexChanging(). if (initialized && selectedIndexChanged && !changingEventDispatched) { // If the active view's REMOVING event or the navigator's // CHANGING event was canceled, prevent the index change if (!indexCanChange(selectedIndex)) { _proposedSelectedIndex = NO_PROPOSED_SELECTION; indexChangedPrevented = true; } } changingEventDispatched = false; if (!indexChangedPrevented) { // If the data provider has changed, the navigator elements have // already been removed, so the following code doesn't need to run if (!selectedIndexAdjusted && !dataProviderChanged && _selectedIndex >= 0 && _selectedIndex < length) { navigator = getElementAt(_selectedIndex) as ViewNavigatorBase; navigator.setActive(false, !maintainNavigationStack); navigator.visible = false; navigator.includeInLayout = false; if (navigator.activeView) navigator.activeView.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); removeNavigatorListeners(navigator); } commitSelection(); if (_selectedIndex >= 0) { // If there is no focus or the item that had focus isn't // on the display list anymore, update the focus to be // the active view or the view navigator updateFocus(); navigator = getElementAt(_selectedIndex) as ViewNavigatorBase; navigator.setActive(true); navigator.visible = true; navigator.includeInLayout = true; addNavigatorListeners(navigator); // Update the states of the controls on the newly activated view navigator. // The updateControlsForView() method will automatically bubble up to all // parents of the navigator. navigator.updateControlsForView(navigator.activeView); // Force a validation of the new navigator to prevent a flicker from // occurring in cases where multiple validation passes are required // to completely validate a view if (initialized) currentContentGroup.validateNow(); if (navigator.activeView) { navigator.activeView.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } } // Dispatch selection change event if (hasEventListener(IndexChangeEvent.CHANGE)) { changeEvent = new IndexChangeEvent(IndexChangeEvent.CHANGE, false, false); changeEvent.oldIndex = oldIndex; changeEvent.newIndex = _selectedIndex; } } selectedIndexAdjusted = false; dataProviderChanged = false; selectedIndexChanged = false; } if (tabBarVisibilityChanged) commitVisibilityChanges(); // When true, this flag prevents tab bar animations from running. This flag // is only set to true if the application received an orientation event this // frame (See ViewNavigatorBase). The flag is reset at the end of commitProperties // so that animations run again. if (disableNextControlAnimation) disableNextControlAnimation = false; // Call base class' commitProperties after the above so that state changes // as a result of overlayControls are caught. This should be okay because // TabbedViewNavigator doesn't need any properties in its base class being // validated to complete the above code super.commitProperties(); // Dispatch the index change event after super.commitProperties() has changed // so the callbacks can deal with state changes performed by commitProperties. if (changeEvent) dispatchEvent(changeEvent); } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function commitSelection():void { _selectedIndex = _proposedSelectedIndex; _proposedSelectedIndex = NO_PROPOSED_SELECTION; lastSelectedIndex = _selectedIndex; if (hasEventListener(FlexEvent.VALUE_COMMIT)) dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } /** * @private * Commits the requested visibility changes made to the action * bar and tab bar. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function commitVisibilityChanges():void { // Can't change the visibility during a view transition if (selectedNavigatorChangingView) return; // If an animation is running, end it if (tabBarVisibilityEffect) tabBarVisibilityEffect.end(); // Change the visibility of the tabBar if the desired state // is different than the current state if (tabBar && showingTabBar != tabBar.visible) { // The animateTabBarVisibility flag is set to true if the // hideTabBar() or showTabBar() methods are called with the // animate flag set to true if (!disableNextControlAnimation && transitionsEnabled && animateTabBarVisbility) { tabBarProps = {target:tabBar, showing:showingTabBar}; tabBarVisibilityEffect = showingTabBar ? createTabBarShowEffect() : createTabBarHideEffect(); tabBarVisibilityEffect.addEventListener(EffectEvent.EFFECT_END, visibilityAnimation_effectEndHandler); tabBarVisibilityEffect.play(); } else { // Since the visibility is not being animated, toggle the state tabBar.visible = tabBar.includeInLayout = showingTabBar; if (activeView) activeView.setTabBarVisible(showingTabBar); } } tabBarVisibilityChanged = false; } /** * Creates the effect to play when the TabBar control is shown. * The produced effect is responsible for animating both the * TabBar and the content group of the navigator. * *

TabbedViewNavigator will expect the includeInLayout * and visible properties of the TabBar to be true * after this effect is run.

* * @return An effect to play when the TabBar control appears. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createTabBarShowEffect():IEffect { return createTabBarVisibilityEffect(true); } /** * Creates the effect to play when the TabBar control is hidden. * The produced effect is responsible for animating both the * TabBar and the content group of the navigator. * *

TabbedViewNavigator expects the includeInLayout * and visible properties of the TabBar to be false * after this effect runs.

* * @return An effect to play when the TabBar control is hidden. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createTabBarHideEffect():IEffect { return createTabBarVisibilityEffect(false); } /** * Creates the animation that will be played when the TabBar is * hidden. * * @return The effect ot play * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function createTabBarVisibilityEffect(showAnimation:Boolean):IEffect { var effect:IEffect; var finalEffect:Parallel = new Parallel(); // Grab initial values tabBarProps.start = captureAnimationValues(tabBar); contentGroupProps = { start:captureAnimationValues(contentGroup) }; // Update actionBar layout properties tabBar.visible = tabBar.includeInLayout = showingTabBar; // Calculate final positions. This method will force a validation prepareTabBarForAnimation(showAnimation); var animate:Animate = new Animate(); animate.target = tabBar; animate.duration = TAB_BAR_ANIMATION_DURATION; animate.motionPaths = new Vector.(); animate.motionPaths.push(new SimpleMotionPath(""y"", tabBarProps.start.y, tabBarProps.end.y)); effect = animate; finalEffect.addChild(effect); // Create content group animation animate = new Animate(); animate.target = contentGroup; animate.duration = TAB_BAR_ANIMATION_DURATION; animate.motionPaths = new Vector.(); animate.motionPaths.push(new SimpleMotionPath(""y"", contentGroupProps.start.y, contentGroupProps.end.y)); animate.motionPaths.push(new SimpleMotionPath(""height"", contentGroupProps.start.height, contentGroupProps.end.height)); contentGroup.includeInLayout = false; finalEffect.addChild(animate); finalEffect.duration = TAB_BAR_ANIMATION_DURATION; return finalEffect; } /** * @private */ private function navigator_elementAddHandler(event:ElementExistenceEvent):void { event.element.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } /** * @private */ private function navigator_elementRemoveHandler(event:ElementExistenceEvent):void { event.element.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } /** * @private * Dispatched when a property on a child navigator changed. */ private function navigator_propertyChangeHandler(event:PropertyChangeEvent):void { itemUpdated(event.target, event.property, event.oldValue, event.newValue); } /** * @private */ override protected function partAdded(partName:String, instance:Object):void { super.partAdded(partName, instance); if (instance == tabBar) { tabBar.addEventListener(IndexChangeEvent.CHANGING, tabBar_indexChanging); tabBar.dataGroup.addEventListener(RendererExistenceEvent.RENDERER_ADD, tabBar_elementAddHandler); tabBar.dataProvider = this; tabBar.requireSelection = true; } } /** * @private */ override protected function partRemoved(partName:String, instance:Object):void { super.partRemoved(partName, instance); if (instance == tabBar) { tabBar.dataGroup.removeEventListener(RendererExistenceEvent.RENDERER_ADD, tabBar_elementAddHandler); tabBar.removeEventListener(IndexChangeEvent.CHANGING, tabBar_indexChanging); tabBar.dataProvider = null; } } /** * @private */ override public function loadViewData(value:Object):void { super.loadViewData(value); var savedStacks:Vector.; var savedSelectedIndex:Number = value.selectedIndex as Number; // By the time this method is called, all skin parts should be // added to the component meaning that it is okay to directly // manipulate the child navigators. if (!isNaN(savedSelectedIndex) && savedSelectedIndex < length) selectedIndex = savedSelectedIndex; savedStacks = value.childrenStates as Vector.; if (savedStacks) { var navigator:ViewNavigatorBase; var len:Number = Math.min(savedStacks.length, length); for (var i:int = 0; i < len; i++) { navigator = getElementAt(i) as ViewNavigatorBase; navigator.loadViewData(savedStacks[i]); } } } /** * @private */ override public function saveViewData():Object { var savedData:Object = super.saveViewData(); var childrenStates:Vector. = new Vector.(); for (var i:int = 0; i < length; i++) childrenStates.push((getElementAt(i) as ViewNavigatorBase).saveViewData()); if (!savedData) savedData = {}; savedData.selectedIndex = selectedIndex; savedData.childrenStates = childrenStates; return savedData; } /** * @private * Redispatches the child navigator's COMPLETE event. */ private function navigator_viewChangeCompleteHandler(event:Event):void { if (hasEventListener(""viewChangeComplete"")) dispatchEvent(event); selectedNavigatorChangingView = false; if (tabBar) tabBar.mouseEnabled = explicitTabBarMouseEnabled; } /** * @private */ private function navigator_viewChangeStartHandler(event:Event):void { selectedNavigatorChangingView = true; // Disable mouse interaction with the tabBar if (tabBar) { explicitTabBarMouseEnabled = tabBar.mouseEnabled; tabBar.mouseEnabled = false; } } /** * @private */ private function tabBar_elementAddHandler(event:RendererExistenceEvent):void { event.target.addEventListener(MouseEvent.CLICK, tabBarRenderer_clickHandler); } /** * @private * Determines if the selection of the tab bar can change. */ private function tabBar_indexChanging(event:IndexChangeEvent):void { if (!indexCanChange(event.newIndex)) { event.preventDefault(); // Clear changing flag changingEventDispatched = false; } } /** * @private */ private function elementRemoveHandler(event:ElementExistenceEvent):void { cleanUpNavigator(event.element as ViewNavigatorBase); internalDispatchEvent(CollectionEventKind.REMOVE, event.element, event.index); // Element removed event is called before the element is removed from the // display list. So if the last navigator is about to be removed, numElements // should be 1 if (numElements == 1) selectedIndex = -1; } /** * @private */ private function elementAddHandler(event:ElementExistenceEvent):void { setupNavigator(event.element as ViewNavigatorBase); internalDispatchEvent(CollectionEventKind.ADD, event.element, event.index); // If the added element is the first view navigator, update the selection // to point to it if (numElements == 1) selectedIndex = 0; } /** * @private * Method is called when a tab is clicked by the user. The default * implementation checks if the clicked tab is currently selected, and if * so, pops the active navigator to its root view. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function tabBarRenderer_clickHandler(event:MouseEvent):void { // lastSelectedIndex is used instead of tabBar.selectedIndex // because by the time this method is called, the tabBar's // proposedSelectedIndex has changed, which causes its selectedIndex // method to return the proposed index instead of the currently // selected index. if ((event.target is IItemRenderer) && (IItemRenderer(event.target).itemIndex == lastSelectedIndex)) { if (selectedNavigator is ViewNavigator) ViewNavigator(selectedNavigator).popToFirstView(); } } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function view_propertyChangeHandler(event:PropertyChangeEvent):void { if (event.property == ""tabBarVisible"") { if (event.newValue) showTabBar(); else hideTabBar(); } else if (event.property == ""overlayControls"") { overlayControls = event.newValue; } } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function visibilityAnimation_effectEndHandler(event:EffectEvent):void { event.target.removeEventListener(EffectEvent.EFFECT_END, visibilityAnimation_effectEndHandler); tabBarVisibilityEffect = null; if (activeView) activeView.setTabBarVisible(tabBarProps.showing); // Check if the visible and cacheAsBitmap properties have been set. These are // only set if the default transitions are used. If developers create their // own animations, these properties won't be set. if (tabBarProps.start != undefined) { tabBar.visible = tabBar.includeInLayout = tabBarProps.end.visible; tabBar.cacheAsBitmap = tabBarProps.start.cacheAsBitmap; } tabBarProps = null; if (contentGroupProps) { contentGroup.includeInLayout = contentGroupProps.start.includeInLayout; contentGroup.cacheAsBitmap = contentGroupProps.start.cacheAsBitmap; // The default tab bar hide and show animation will animate the width and height // of the navigator's contentGroup. If the explicitWidth or explicitHeight properties // were NaN before the animation, they'll be set to real values by the animation. As // a result, it is necessary to restore them to NaN so that layout properly sizes these // components. if (isNaN(contentGroupProps.start.explicitHeight)) contentGroup.explicitHeight = NaN; if (isNaN(contentGroupProps.start.explicitWidth)) contentGroup.explicitWidth = NaN; if (!isNaN(contentGroupProps.start.percentWidth)) contentGroup.percentWidth = contentGroupProps.start.percentWidth; if (!isNaN(contentGroupProps.start.percentHeight)) contentGroup.percentHeight = contentGroupProps.start.percentHeight; contentGroupProps = null; } } //-------------------------------------------------------------------------- // // Methods: ISelectableList // //-------------------------------------------------------------------------- //---------------------------------- // selectedIndex //---------------------------------- /** * @private * The proposed selected index. This is a temporary variable that is * used until the selected index is committed. */ protected var _proposedSelectedIndex:int = NO_PROPOSED_SELECTION; /** * @private * The backing variable for selectedIndex. */ protected var _selectedIndex:int = NO_PROPOSED_SELECTION; [Bindable(""change"")] [Bindable(""valueCommit"")] /** * The 0-based index of the selected view navigator, or -1 if none is selected. * Setting the selectedIndex property deselects the currently selected * navigator and selects the navigator at the specified index. * *

The value is always between -1 and (navigators.length - 1). * If items at a lower index than selectedIndex are * removed from the component, the selected index is adjusted downward * accordingly.

* *

If the selected item is removed, the selected index is set to:

* *
    *
  • -1 if there are no remaining items.
  • *
  • selectedIndex - 1 if there is at least one item.
  • *
* * @default -1 * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get selectedIndex():int { if (_proposedSelectedIndex != NO_PROPOSED_SELECTION) return _proposedSelectedIndex; return _selectedIndex; } /** * @private */ public function set selectedIndex(value:int):void { if (!dataProviderChanged && value == selectedIndex) return; if (activeView) activeView.dispatchEvent(new Event(""_navigationChange_"")); _proposedSelectedIndex = value; selectedIndexChanged = true; invalidateProperties(); } /** * @private * This method determines the navigator can change its selected index. * This function will be called if the selection changed on the * tab bar, or if the selectedIndex property has changed. */ private function indexCanChange(proposedSelection:int):Boolean { changingEventDispatched = true; if (!canRemoveCurrentView()) return false; if (hasEventListener(IndexChangeEvent.CHANGING)) { var e:IndexChangeEvent = new IndexChangeEvent(IndexChangeEvent.CHANGING, false, true); e.oldIndex = _selectedIndex; e.newIndex = proposedSelection; if (!dispatchEvent(e)) return false; } return true; } //---------------------------------- // length //---------------------------------- /** * The number of child view navigators being managed by the * this component. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get length():int { return numElements; } /** * Add the specified view navigator to the end of the list. * Equivalent to calling addItemAt(item, length);. * * @param item The view navigator to add. * It must extend the ViewNavigatorBase class. * * @see spark.components.supportClasses.ViewNavigatorBase * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function addItem(item:Object):void { addItemAt(item, length); } /** * Add the view navigator at the specified index. * Any view navigator that was after this index is moved down by one. * * @param item The view navigator to add. * It must extend the ViewNavigatorBase class. * * @param index The index at which to place the item. * * @throws RangeError If index is less than 0 or greater than the length * * @see spark.components.supportClasses.ViewNavigatorBase * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function addItemAt(item:Object, index:int):void { // If the added type is not a ViewNavigatorBase, we ignore the call // TODO (chiedozi): Consider throwing an exception here if (!(item is ViewNavigatorBase)) return; if (index < 0 || index > length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } setupNavigator(ViewNavigatorBase(item)); addElementAt(ViewNavigatorBase(item), index); if (selectedIndex == NO_PROPOSED_SELECTION || numElements == 1) { selectedIndex = 0; } else if (index <= selectedIndex) { selectedIndex++; selectedIndexAdjusted = true; } } /** * Get the view navigator object at the specified index. * * @param index The index in the list from which to retrieve the item. * * @param prefetch Indicating both the direction and amount of items * to fetch during the request, should the item not be local. * * @return The navigator at the specified index, or null if there is none. * * @throws RangeError If the index < 0 or index >= length * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function getItemAt(index:int, prefetch:int = 0):Object { if (index < 0 || index >= length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } return getElementAt(index); } /** * Return the index of the view navigator if it is in the list * of view navigators. * * @param item The view navigator object to locate. * * @return The index of the view navigator, or -1 if the item is not in the list. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function getItemIndex(item:Object):int { return getElementIndex(item as ViewNavigatorBase); } /** * Notify external components that a property on a view navigator has * been updated. * * @param item The view navigator that was updated. * * @param property A String, QName, or int * specifying the property that was updated. * * @param oldValue The old value of that property. * If property was null, this can be the old value of the item. * * @param newValue The new value of that property. * If property was null, there's no need to specify this * as the item is assumed to be the new value. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function itemUpdated(item:Object, property:Object = null, oldValue:Object = null, newValue:Object = null):void { var event:PropertyChangeEvent = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE); event.kind = PropertyChangeEventKind.UPDATE; event.source = item; event.property = property; event.oldValue = oldValue; event.newValue = newValue; internalDispatchEvent(CollectionEventKind.UPDATE, event); } /** * Remove all child view navigators from the navigator. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function removeAll():void { // Deactive the active navigator and its view if (selectedNavigator) selectedNavigator.setActive(false); // Remove all navigators navigators = null; } /** * Removes the specified item from this list, should it exist. * Relies on ArrayList implementation * * @param item Object reference to the item that should be removed. * @return Boolean indicating if the item was removed. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Apache Flex 4.10 */ public function removeItem( item:Object ):Boolean { var element:IVisualElement = removeElement(item as ViewNavigatorBase); return element != null; } /** * Remove the view navigator at the specified index and return it. * The index of any items that were after this index are decreased by one. * * @param index The index from which to remove the item. * * @return The item that was removed. * * @throws RangeError If index < 0 or index >= length. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function removeItemAt(index:int):Object { if (index < 0 || index >= length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } if (index <= selectedIndex) { selectedIndex--; selectedIndexAdjusted = true; } var removed:Object = removeElementAt(index); return removed; } /** * Add the view navigator at the specified index. * If an item was already at that index, the new item replaces it, * and it is returned. * * @param item The view navigator to place at the index. * * @param index The index at which to place the navigator. * * @return The navigator that was replaced, or null if none. * * @throws RangeError If index is less than 0 or greater than or equal to length * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function setItemAt(item:Object, index:int):Object { // If the added type is not a ViewNavigatorBase, we ignore the call // TODO (chiedozi): Consider throwing an exception here if (!(item is ViewNavigator)) return null; if (index < 0 || index >= length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } var oldItem:Object = removeElementAt(index); addElementAt(item as ViewNavigatorBase, index); // Let the navigator know that the item at the selectedIndex changed. // The commitProperties method will pick this up. if (index == selectedIndex) { selectedIndexAdjusted = true; invalidateProperties(); } if (hasEventListener(CollectionEvent.COLLECTION_CHANGE)) { var updateInfo:PropertyChangeEvent; updateInfo = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE); updateInfo.kind = PropertyChangeEventKind.UPDATE; updateInfo.oldValue = oldItem; updateInfo.newValue = item; updateInfo.property = index; internalDispatchEvent(CollectionEventKind.REPLACE, updateInfo, index); } return oldItem; } /** * Return an Array that is populated in the same order as the IList * implementation. * * @return The Array. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function toArray():Array { return contentGroup.getMXMLContent(); } /** * @private * Dispatches a collection event with the specified information. * * @param kind String indicates what the kind property of the event should be * @param item Object reference to the item that was added or removed * @param location int indicating where in the source the item was added. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function internalDispatchEvent(kind:String, item:Object = null, location:int = -1):void { if (hasEventListener(CollectionEvent.COLLECTION_CHANGE)) { var event:CollectionEvent = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE); event.kind = kind; event.items.push(item); event.location = location; dispatchEvent(event); } // now dispatch a complementary PropertyChangeEvent if (hasEventListener(PropertyChangeEvent.PROPERTY_CHANGE) && (kind == CollectionEventKind.ADD || kind == CollectionEventKind.REMOVE)) { var objEvent:PropertyChangeEvent = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE); objEvent.property = location; if (kind == CollectionEventKind.ADD) objEvent.newValue = item; else objEvent.oldValue = item; dispatchEvent(objEvent); } } /** * @private * If the item is an IEventDispatcher watch it for updates. * This is called by addItemAt and when the source is initially * assigned. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function startTrackingUpdates(item:Object):void { if (item && (item is IEventDispatcher)) { IEventDispatcher(item).addEventListener( PropertyChangeEvent.PROPERTY_CHANGE, navigator_propertyChangeHandler, false, 0, true); } } /** * @private * If the item is an IEventDispatcher stop watching it for updates. * This is called by removeItemAt, removeAll, and before a new * source is assigned. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function stopTrackingUpdates(item:Object):void { if (item && item is IEventDispatcher) { IEventDispatcher(item).removeEventListener( PropertyChangeEvent.PROPERTY_CHANGE, navigator_propertyChangeHandler); } } } }",12223,True,2590.1691113692477,median "import resources; import util.target_search; import regions.regions; import saving; import attributes; from generic_effects import RegionChangeable, LeaderChangeable; from influence_global import giveRandomReward, DiplomacyEdictType; from designs import getDesignMesh; from statuses import getStatusID; MeshDesc shipMesh; //Amount of points per unit of size of a ship const double SHIP_SIZE_POINTS = 0.0; //Rate of repair in combat const double COMBAT_REPAIR_MOD = 1.0 / 4.0; //Amount of effectiveness gained from energy = size const float ENERGY_EFFECTIVENESS = 1.25f; //Threshold at which lack of supply starts causing efficiency loss const float SUPPLY_THRESHOLD = 0.25f; //Lowest efficiency supply can make a fleet go down to const float SUPPLY_EFFICIENCY = 0.2f; //Supply rate in trade border systems const float SUPPLY_TRADE_RATE = 0.26f; //Supply rate in unowned systems const float SUPPLY_UNOWNED_RATE = 0.12f; //Rate at which supression recovers const float SUPPRESSION_REGEN = 0.05f; //Chance of extinguishing fire per second const float EXTINGUISH_CHANCE = 0.2f; //Fire damage-per-second per size const float FIRE_DPS = 0.25; tidy class ShipScript { Object@ lastHitBy; Empire@ killCredit; uint bpStatusID = 0; bool barDelta = false, onFire = false, needRepair = true, shieldDelta = false; int prevSupply = 0; int currentMaintenance = 0; float mass = 0.f; float massBonus = 0.f; float currentRepair = 0.f; float currentRepairCost = 0.f; float shipEffectiveness = 0.f; float bonusEffectiveness = 0.f; float suppression = 0.f; float wreckage = 0.f; float shieldRegen = 0.f; Object@ cachedLeader; const Design@ retrofitTo; const Design@ queuedRetrofit; float timer = 0.f, bpTimer = 0.f; float supplyBonus = 0.f; int disableRegionVision = 0; int holdFire = 0; float movementAccel = 0; float bonusShield = 0; float supplyConsumeFactor = 1.f; ShipScript() { } void save(Ship& ship, SaveFile& file) { saveObjectStates(ship, file); file << cast(ship.Mover); if(ship.hasLeaderAI) { file << true; file << cast(ship.LeaderAI); } else { file << false; } if(ship.hasSupportAI) { file << true; file << cast(ship.SupportAI); } else { file << false; } if(ship.hasAbilities) { file << true; file << cast(ship.Abilities); } else { file << false; } if(ship.hasStatuses) { file << true; file << cast(ship.Statuses); } else { file << false; } if(ship.hasCargo) { file << true; file << cast(ship.Cargo); } else { file << false; } if(ship.hasConstruction) { file << true; file << cast(ship.Construction); } else { file << false; } if(ship.hasOrbit) { file << true; file << cast(ship.Orbit); } else { file << false; } file << currentMaintenance; file << ship.isFree; file << ship.isFTLing; file << ship.delayFTL; file << prevSupply; file << ship.Energy; file << ship.MaxEnergy; file << ship.Supply; file << ship.MaxSupply; file << ship.formationDest; ship.blueprint.save(ship, file); file << ship.Leader; file << ship.RetrofittingAt; file << retrofitTo; file << queuedRetrofit; file << suppression; file << wreckage; file << onFire; file << supplyBonus; file << massBonus; file << ship.Shield; file << ship.MaxShield; file << shieldRegen; file << disableRegionVision; file << holdFire; file << movementAccel; file << bonusShield; file << supplyConsumeFactor; file << bonusEffectiveness; } void load(Ship& ship, SaveFile& file) { timer = -float(uint8(ship.id)) / 255.f; bpTimer = timer - 0.5f; loadObjectStates(ship, file); file >> cast(ship.Mover); bool has = false; file >> has; if(has) { ship.activateLeaderAI(); file >> cast(ship.LeaderAI); } file >> has; if(has) { ship.activateSupportAI(); file >> cast(ship.SupportAI); } file >> has; if(has) { ship.activateAbilities(); file >> cast(ship.Abilities); } file >> has; if(has) { ship.activateStatuses(); file >> cast(ship.Statuses); } if(file >= SV_0122) { file >> has; if(has) { ship.activateCargo(); file >> cast(ship.Cargo); } } if(file >= SV_0108) { file >> has; if(has) { ship.activateConstruction(); file >> cast(ship.Construction); } } if(file >= SV_0060) { file >> has; if(has) { ship.activateOrbit(); file >> cast(ship.Orbit); } } file >> currentMaintenance; file >> ship.isFree; file >> ship.isFTLing; file >> ship.delayFTL; file >> prevSupply; file >> ship.Energy; file >> ship.MaxEnergy; file >> ship.Supply; file >> ship.MaxSupply; file >> ship.formationDest; ship.blueprint.load(ship, file); @ship.Leader = file.readObject(); file >> ship.RetrofittingAt; file >> retrofitTo; file >> queuedRetrofit; file >> suppression; file >> wreckage; file >> onFire; if(file >= SV_0077) file >> supplyBonus; if(file >= SV_0081) file >> massBonus; if(file >= SV_0092) { file >> ship.Shield; file >> ship.MaxShield; file >> shieldRegen; } if(file >= SV_0104) { file >> disableRegionVision; file >> holdFire; } if(file >= SV_0117) file >> movementAccel; getDesignMesh(ship.owner, ship.blueprint.design, shipMesh); bindMesh(ship, shipMesh); if(file >= SV_0138) file >> bonusShield; if(file >= SV_0147) file >> supplyConsumeFactor; if(file >= SV_0149) file >> bonusEffectiveness; if(ship.hasSupportAI) ship.supportPostLoad(); } bool get_isStation(Ship& ship) { return ship.blueprint.design.hasTag(ST_Station); } void setHoldFire(bool value) { if(value) holdFire += 1; else holdFire -= 1; } bool getHoldFire() { return holdFire > 0 || inFTL; } void setDisableRegionVision(bool value) { if(value) disableRegionVision += 1; else disableRegionVision -= 1; } bool getDisableRegionVision() { return disableRegionVision > 0; } void addBonusEffectiveness(float mod) { bonusEffectiveness += mod; } void modMass(Ship& ship, float amount) { massBonus += amount; ship.blueprint.statusID++; } float getMass() { return max(mass + massBonus, 0.01f); } float getBaseMass() { return max(mass, 0.01f); } void modHPFactor(Ship& ship, float pct) { auto@ bp = ship.blueprint; bp.hpFactor += pct; bp.delta = true; } void modBonusShield(Ship& ship, float mod) { bonusShield += mod; ship.blueprint.statusID++; } void shieldDamage(Ship& ship, double amount) { ship.Shield = clamp(ship.Shield - amount, 0.0, max(ship.MaxShield, ship.Shield)); } void postLoad(Ship& ship) { if(ship.hasLeaderAI) { ship.leaderPostLoad(); Node@ node = ship.getNode(); if(node !is null) node.animInvis = true; } cacheStats(ship); updateStats(ship); if(ship.region !is null) { Node@ node = ship.getNode(); if(node !is null) node.hintParentObject(ship.region, false); } } void init(Ship& ship) { timer = -float(uint8(ship.id)) / 255.f; bpTimer = timer - 0.5f; } uint moneyType(Ship& ship) { const Design@ dsg = ship.blueprint.design; if(dsg !is null && dsg.hasTag(ST_Station)) return MoT_Orbitals; return MoT_Ships; } stat::EmpireStat statType(Ship& ship) { const Design@ dsg = ship.blueprint.design; if(dsg !is null && dsg.hasTag(ST_Station)) return stat::Stations; return stat::Ships; } void postInit(Ship& ship) { cacheStats(ship); updateStats(ship, true); if(ship.hasLeaderAI) ship.Supply = ship.MaxSupply; else ship.Supply = 0; if(ship.hasLeaderAI) { ship.leaderInit(); ship.activateStatuses(); ship.activateAbilities(); if(ship.owner.valid) ship.owner.recordStatDelta(statType(ship), 1); auto@ node = ship.getNode(); if(node !is null) node.animInvis = true; } else{ ship.supportInit(); } if(ship.owner !is null && ship.owner.valid) { if(ship.hasLeaderAI) ship.owner.points += int(double(ship.blueprint.design.size) * SHIP_SIZE_POINTS); if(ship.hasLeaderAI) { ship.owner.TotalFlagshipsBuilt += 1; ship.owner.TotalFlagshipsActive += 1; } else { ship.owner.TotalSupportsBuilt += 1; ship.owner.TotalSupportsActive += 1; } } ship.startEffects(); } void startEffects(Ship& ship) { if(ship.blueprint.design.hasTag(ST_Ability)) { if(!ship.hasAbilities) ship.activateAbilities(); ship.initAbilities(ship.blueprint.design); } ship.blueprint.start(ship); } int get_maintenanceCost() { return currentMaintenance; } void setHealthPct(Ship& obj, float pct) { if(pct >= 0.999f) return; auto@ bp = obj.blueprint; vec2i size = bp.design.hull.gridSize; DamageEvent evt; evt.pierce = 0.f; @evt.obj = obj; @evt.target = obj; for(int x = 0; x < size.x; ++x) { for(int y = 0; y < size.y; ++y) { auto@ status = bp.getHexStatus(x, y); if(status !is null && status.hp != 0) { evt.damage = bp.design.variable(vec2u(x,y), HV_HP) * (1.f - pct); if(evt.damage > 0.001f) bp.damage(obj, evt, vec2u(x, y)); } } } needRepair = true; bp.delta = true; } void makeNotFree(Ship& ship) { if(ship.isFree) { if(ship.owner !is null && ship.owner.valid) { currentMaintenance = max(ship.blueprint.design.total(HV_MaintainCost), 0.0); ship.owner.modMaintenance(currentMaintenance, moneyType(ship)); } else { currentMaintenance = 0; } ship.isFree = false; } } void startRetrofit(Ship& ship, Object@ from, const Design@ to) { if(ship.RetrofittingAt !is null) return; @ship.RetrofittingAt = from; @retrofitTo = to; } void stopRetrofit(Ship& ship, Object@ from) { if(ship.RetrofittingAt is from) { @ship.RetrofittingAt = null; @retrofitTo = null; } } void completeRetrofit(Ship& ship, Object@ from) { if(ship.RetrofittingAt is from) { makeNotFree(ship); @queuedRetrofit = retrofitTo; @ship.RetrofittingAt = null; @retrofitTo = null; } } void cacheStats(Ship& ship) { ship.MaxDPS = ship.blueprint.design.total(SV_DPS); if(ship.hasLeaderAI) ship.MaxSupply = ship.blueprint.design.total(SV_SupplyCapacity) + supplyBonus; else ship.MaxSupply = ship.blueprint.design.total(SV_SupportSupplyCapacity) + supplyBonus; mass = ship.blueprint.design.total(HV_Mass); /*ship.MaxEnergy = ship.blueprint.design.total(SV_EnergyCapacity);*/ ship.MaxEnergy = 0; const Design@ dsg = ship.blueprint.design; ship.hasVectorMovement = ship.isStation || (dsg.hasTag(ST_VectorThrust) && !dsg.hasTag(ST_TurnToThrust)); } void modSupplyBonus(Ship& ship, float amount) { supplyBonus += amount; if(ship.hasLeaderAI) ship.MaxSupply = ship.blueprint.design.total(SV_SupplyCapacity) + supplyBonus; else ship.MaxSupply = ship.blueprint.design.total(SV_SupportSupplyCapacity) + supplyBonus; if(ship.MaxSupply > 0 && amount < 0) ship.Supply += (ship.Supply / ship.MaxSupply) * amount; } float curThrust = 0.f; float curTurnThrust = 0.f; void updateAccel(Ship& ship) { float thrust = curThrust; if(ship.hasLeaderAI) { float leaderAccel = thrust / max(mass + massBonus, 0.01f); float supportAccel = ship.slowestSupportAccel; float resultAccel = leaderAccel; if(supportAccel > 0.0f && supportAccel * 0.75f < leaderAccel) resultAccel = supportAccel * 0.75f; if(resultAccel > movementAccel || leaderAccel < movementAccel || !ship.isMoving) { ship.maxAcceleration = resultAccel; movementAccel = resultAccel; } } else { if(ship.isRaiding) thrust += ship.blueprint.getEfficiencySum(SV_BoostThrust); float accel = thrust / max(mass + massBonus, 0.01f); ship.maxAcceleration = accel; } } void updateStats(Ship& ship, bool init = false) { const Design@ dsg = ship.blueprint.design; //Set the mover's maximum acceleration based on thrust curThrust = ship.blueprint.getEfficiencySum(SV_Thrust); curTurnThrust = ship.blueprint.getEfficiencySum(SV_TurnThrust); if(curTurnThrust != 0) ship.rotationSpeed = max(curTurnThrust / max(mass, 0.01f), 0.005f); if(init) ship.maxAcceleration = curThrust / max(mass + massBonus, 0.01f); else updateAccel(ship); //Record the used command float commandUsed = dsg.variable(ShV_REQUIRES_Command); float powerUsed = dsg.variable(ShV_REQUIRES_Power); //Record DPS ship.DPS = ship.blueprint.getEfficiencySum(SV_DPS); //Update shield stats double maxShield = ship.blueprint.getEfficiencySum(SV_ShieldCapacity); if(maxShield > 0) maxShield += bonusShield; if(maxShield != ship.MaxShield) { if(maxShield == 0) { ship.Shield = 0; ship.MaxShield = 0; shieldRegen = 0; } else if(ship.MaxShield > 0) { ship.Shield = maxShield * (ship.Shield / ship.MaxShield); ship.MaxShield = maxShield; shieldRegen = ship.blueprint.getEfficiencySum(SV_ShieldRegen); } else { ship.MaxShield = maxShield; shieldRegen = ship.blueprint.getEfficiencySum(SV_ShieldRegen); } shieldDelta = true; } //Set the supply capacity of the ship int supply = ship.blueprint.getEfficiencySum(SV_SupportCapacity); if(supply != prevSupply) { ship.modSupplyCapacity(supply - prevSupply); prevSupply = supply; } //Modify ship efficiency based on available command float commandAvail = ship.blueprint.getEfficiencySum(SV_Command); if(commandAvail >= commandUsed || commandUsed <= 0.0) shipEffectiveness = 1.f; else if(commandAvail == 0.f && dsg.total(SV_Command) == 0.f) shipEffectiveness = 1.f; else shipEffectiveness = float(commandAvail) / commandUsed; shipEffectiveness *= (1.f + bonusEffectiveness); //Low power also decreases effectiveness if(powerUsed > 0) { float powerAvail = ship.blueprint.getEfficiencySum(SV_Power); if(powerAvail < powerUsed) shipEffectiveness *= sqr(powerAvail / powerUsed); } float effectiveness = shipEffectiveness; if(suppression > 0.f) effectiveness /= 1.f + suppression; { double minRange = INFINITY, maxRange = -INFINITY; double minRaid = INFINITY, maxRaid = -INFINITY; for(uint i = 0, cnt = dsg.subsystemCount; i < cnt; ++i) { auto@ subsys = dsg.subsystems[i]; if(subsys.type.hasTag(ST_IgnoreRange)) continue; bool forRaid = subsys.type.hasTag(ST_RangeForRaid); for(uint j = 0, jcnt = subsys.effectorCount; j < jcnt; ++j) { double range = subsys.effectors[j].range; if(!forRaid) { if(range < minRange) minRange = range; if(range > maxRange) maxRange = range; } if(range < minRaid) minRaid = range; if(range > maxRaid) maxRaid = range; } } if(!ship.hasLeaderAI) ship.supportEngageRange = min(minRange, minRaid); ship.minEngagementRange = minRange; ship.maxEngagementRange = maxRange; } if(!ship.hasLeaderAI) { Object@ leader = ship.Leader; if(leader !is null) effectiveness *= leader.getFleetEffectiveness(); else effectiveness *= SUPPLY_EFFICIENCY; ship.blueprint.shipEffectiveness = effectiveness; } else { ship.blueprint.shipEffectiveness = double(effectiveness) * double(ship.getFleetEffectiveness()); } //Store the amount of repair we have available currentRepair = ship.blueprint.getEfficiencySum(SV_Repair); currentRepairCost = ship.blueprint.getEfficiencySum(SV_RepairSupplyCost); //Check if we should update our maintenance if(!ship.isFree && ship.owner !is null && ship.owner.valid) { int maint = max(ship.blueprint.design.total(HV_MaintainCost), 0.0); if(maint != currentMaintenance) { ship.owner.modMaintenance(maint - currentMaintenance, moneyType(ship)); currentMaintenance = maint; } } bpStatusID = ship.blueprint.statusID; } void scuttle(Ship& ship) { ship.destroy(); } Object@ getLastHitBy() { return lastHitBy; } void destroy(Ship& ship) { if(ship.owner !is null && ship.owner.valid && currentMaintenance != 0) ship.owner.modMaintenance(-currentMaintenance, moneyType(ship)); if(ship.inCombat) { double regain = ship.owner.ShipCostRegain; if(regain > 0.001) { regain = floor(regain * getBuildCost(ship.blueprint.design)); if(regain >= 1.0) ship.owner.addBonusBudget(int(regain)); } } //Assuming we've been hit recently, the likely cause of death is explosion if(killCredit !is null && !game_ending) { auto size = ship.blueprint.design.size; if(size < 16) playParticleSystem(""ShipExplosionLight"", ship.position, ship.rotation, ship.radius, ship.visibleMask); else playParticleSystem(""ShipExplosion"", ship.position, ship.rotation, ship.radius, ship.visibleMask); if(size > 64) playParticleSystem(""ShipExplosionExtra"", ship.position, ship.rotation, ship.radius, ship.visibleMask); if(size >= 200) playParticleSystem(""ShipExplosionLong"", ship.position, ship.rotation, ship.radius, ship.visibleMask); auto@ region = ship.region; if(region !is null) { uint debris = uint(log(size) / log(2.0)); if(debris > 0) region.addShipDebris(ship.position, debris); if(killCredit !is ship.owner && ship.hasLeaderAI) region.grantExperience(killCredit, size * config::EXPERIENCE_GAIN_FACTOR, combatOnly=true); } if(ship.hasLeaderAI && currentMaintenance != 0) { Empire@ master = killCredit.SubjugatedBy; if(master !is null && master.getEdictType() == DET_Conquer) { if(master.getEdictEmpire() is ship.owner) { giveRandomReward(killCredit, double(currentMaintenance) / 100.0); } } double reward = killCredit.DestroyShipReward + ship.owner.ShipDestroyBounty; if(reward > 0.001) { reward = floor(reward * currentMaintenance); if(reward >= 1.0) killCredit.addBonusBudget(int(reward)); } if(ship.owner.major && ship.getFleetMaxStrength() >= 1000.0) killCredit.modAttribute(EA_EnemyFlagshipsDestroyed, AC_Add, 1.0); } } if(ship.owner !is null && ship.owner.valid) { if(ship.hasLeaderAI) { ship.owner.points -= int(double(ship.blueprint.design.size) * SHIP_SIZE_POINTS); ship.owner.recordStatDelta(statType(ship), -1); } if(killCredit !is ship.owner) ship.owner.recordStatDelta(stat::ShipsLost, 1); } if(lastHitBy !is null && lastHitBy !is ship) ship.lastHit = lastHitBy.id; if(ship.hasSupportAI) { ship.supportDestroy(); if(ship.owner !is null) ship.owner.TotalSupportsActive -= 1; } else if(ship.hasLeaderAI) { ship.leaderDestroy(); if(ship.owner !is null) ship.owner.TotalFlagshipsActive -= 1; } ship.blueprint.destroy(ship); if(ship.hasStatuses) ship.destroyStatus(); if(ship.hasConstruction) ship.destroyConstruction(); if(ship.hasAbilities) ship.destroyAbilities(); if(killCredit !is null && killCredit !is ship.owner && killCredit.valid) killCredit.recordStatDelta(stat::ShipsDestroyed, 1); leaveRegion(ship); } bool onOwnerChange(Ship& ship, Empire@ prevOwner) { if(prevOwner !is null && prevOwner.valid) { if(currentMaintenance != 0) prevOwner.modMaintenance(-currentMaintenance, moneyType(ship)); if(ship.hasLeaderAI) { prevOwner.TotalFlagshipsActive -= 1; prevOwner.recordStatDelta(statType(ship), -1); prevOwner.points -= int(double(ship.blueprint.design.size) * SHIP_SIZE_POINTS); } else prevOwner.TotalSupportsActive -= 1; } if(ship.owner !is null && ship.owner.valid) { if(currentMaintenance != 0) ship.owner.modMaintenance(currentMaintenance, moneyType(ship)); if(ship.hasLeaderAI) { ship.owner.TotalFlagshipsActive += 1; ship.owner.recordStatDelta(statType(ship), 1); ship.owner.points += int(double(ship.blueprint.design.size) * SHIP_SIZE_POINTS); } else ship.owner.TotalSupportsActive += 1; } if(ship.hasAbilities) ship.abilityOwnerChange(prevOwner, ship.owner); if(ship.hasStatuses) ship.changeStatusOwner(prevOwner, ship.owner); regionOwnerChange(ship, prevOwner); if(ship.hasLeaderAI) ship.leaderChangeOwner(prevOwner, ship.owner); ship.blueprint.ownerChange(ship, prevOwner, ship.owner); return false; } bool consumeEnergy(Ship& ship, double amount) { if(ship.Energy < amount) return false; ship.Energy -= amount; return true; } bool consumeMinSupply(Ship& ship, double amount) { if(ship.Supply >= amount) { ship.Supply = max(0.0, ship.Supply - amount); barDelta = true; return true; } else { return false; } } void modSupplyConsumeFactor(float mod) { supplyConsumeFactor += mod; } void consumeSupply(Ship& ship, double amount) { if(ship.hasLeaderAI) { ship.Supply = max(0.0, ship.Supply - amount * max(supplyConsumeFactor, 0.f)); barDelta = true; } else { if(ship.isDetached) { ship.Supply = max(0.0, ship.Supply - amount * max(supplyConsumeFactor, 0.f)); barDelta = true; } else { Ship@ lead = cast(cachedLeader); if(lead !is null) { lead.consumeSupply(amount * max(supplyConsumeFactor, 0.f)); return; } } } } void consumeSupplyPct(Ship& ship, double pct) { ship.Supply = max(0.0, ship.Supply - pct * ship.MaxSupply * max(supplyConsumeFactor, 0.f)); barDelta = true; } void refundEnergy(Ship& ship, double amount) { ship.Energy = min(ship.MaxEnergy, ship.Energy + amount); barDelta = true; } void refundSupply(Ship& ship, double amount) { ship.Supply = min(ship.MaxSupply, ship.Supply + amount); barDelta = true; } void repairShip(Ship& ship, double amount) { ship.blueprint.repair(ship, amount); } void mangle(double amount) { wreckage += amount; } void suppress(double amount) { suppression += amount; } void startFire() { onFire = true; } void triggerLeaderChange(Ship& ship, Object@ prevLeader, Object@ newLeader) { if(ship.blueprint.design.dataCount != 0) { uint hookN = 0; SubsystemEvent evt; @evt.obj = ship; @evt.design = ship.blueprint.design; @evt.blueprint = ship.blueprint; for(uint i = 0, cnt = ship.blueprint.design.subsystemCount; i < cnt; ++i) { auto@ subsys = ship.blueprint.design.subsystems[i]; for(uint n = 0, ncnt = subsys.hookCount; n < ncnt; ++n) { auto@ cls = cast(subsys.hooks[n]); if(cls !is null) { @evt.subsystem = subsys; @evt.data = ship.blueprint.getHookData(hookN); cls.leaderChange(evt, prevLeader, newLeader); } hookN += 1; } } } } float combatTimer = 0.f; bool prevEngaged = false; bool inFTL = false; void occasional_tick(Ship& ship, float time) { Empire@ owner = ship.owner; Region@ reg = ship.region; Ship@ shipLeader = cast(cachedLeader); bool regionChanged = updateRegion(ship, takeVision=false); inFTL = ship.inFTL; if(regionChanged) { if(ship.hasLeaderAI) { ship.leaderRegionChanged(); if(ship.hasStatuses) ship.changeStatusRegion(reg, ship.region); } else { Node@ node = ship.getNode(); if(node !is null) node.hintParentObject(ship.region, false); } if(ship.blueprint.design.dataCount != 0) { uint hookN = 0; SubsystemEvent evt; @evt.obj = ship; @evt.design = ship.blueprint.design; @evt.blueprint = ship.blueprint; for(uint i = 0, cnt = ship.blueprint.design.subsystemCount; i < cnt; ++i) { auto@ subsys = ship.blueprint.design.subsystems[i]; for(uint n = 0, ncnt = subsys.hookCount; n < ncnt; ++n) { auto@ cls = cast(subsys.hooks[n]); if(cls !is null) { @evt.subsystem = subsys; @evt.data = ship.blueprint.getHookData(hookN); cls.regionChange(evt, reg, ship.region); } hookN += 1; } } } @reg = ship.region; } //Take vision from region if(reg !is null) { if(disableRegionVision <= 0 && (shipLeader is null|| !shipLeader.getDisableRegionVision())) ship.donatedVision |= reg.DonateVisionMask; } //Update in combat flags bool engaged = ship.engaged; if(cachedLeader !is null) { if(engaged) cachedLeader.engaged = true; if(cachedLeader.inCombat) engaged = true; } if(holdFire > 0 || inFTL || (shipLeader !is null && (shipLeader.getHoldFire() || (ship.isDetached && ship.Supply <= 0.001)))) ship.blueprint.holdFire = true; else ship.blueprint.holdFire = false; if(engaged) combatTimer = 5.f; else combatTimer -= time; { bool nowCombat = combatTimer > 0.f; if(ship.inCombat != nowCombat) { ship.inCombat = nowCombat; barDelta = true; } } ship.engaged = false; //Deal with combat facing Object@ target = ship.getAttackTarget(); if(engaged || target !is null) { if(target is null) @target = ship.blueprint.getCombatTarget(); if(target is null) @target = findEnemy(ship, ship, owner, ship.position, 500.0); if(target !is null) { //Always face the fleet as a whole { Ship@ othership = cast(target); if(othership !is null) { Object@ leader = othership.Leader; if(leader !is null) @target = leader; } } //Find optimal facing vec3d facing = ship.blueprint.getOptimalFacing(SV_DPS); vec3d diff = target.position - ship.position; diff.normalize(); //Rotate so that target rotation * facing = diff quaterniond rot = quaterniond_fromVecToVec(facing, diff); ship.setCombatFacing(rot); if(ship.hasLeaderAI) { //Order a random support to assist uint cnt = ship.supportCount; if(cnt > 0) { uint attackWith = max(1, cnt / 8); for(uint i = 0, off = randomi(0,cnt-1); i < attackWith; ++i) { Object@ sup = ship.supportShip[(i+off) % cnt]; if(sup !is null) sup.supportAttack(target); } } } } else ship.clearCombatFacing(); if(reg !is null) reg.EngagedMask |= owner.mask; } else if(prevEngaged) { ship.clearCombatFacing(); } prevEngaged = engaged; bool isContested = engaged || (reg !is null && reg.ContestedMask & owner.mask != 0); //Deal with energy charge float fleetEffectiveness = 1.f; if(ship.MaxEnergy > 0 && ship.Energy < ship.MaxEnergy) { if((reg !is null && reg.TradeMask & owner.TradeMask.value != 0 && !engaged) || owner.GlobalCharge) { /*float chargeRate = ship.blueprint.getEfficiencySum(SV_ChargeRate);*/ float chargeRate = 0.f; float amt = min(chargeRate * time, ship.MaxEnergy - ship.Energy); amt = owner.consumeEnergy(amt); if(amt > 0.f) { ship.Energy = min(ship.Energy + amt, ship.MaxEnergy); barDelta = true; } } } if(ship.hasSupportAI) { ship.supportTick(time); if(cachedLeader !is null) ship.seeableRange = cachedLeader.seeableRange; else ship.seeableRange = FLOAT_INFINITY; } else if(ship.hasLeaderAI) { ship.commandTick(); if(ship.Energy > 0) { //Calculate extra fleet effectiveness based on energy //relative to ship size and supply. float size = ship.blueprint.design.size; fleetEffectiveness *= 1.f + ENERGY_EFFECTIVENESS * (ship.Energy / size); } if(ship.MaxSupply > 0) { //Supply recharge if(ship.Supply < ship.MaxSupply) { float chargeRate = ship.blueprint.getEfficiencySum(SV_SupplyRate); float amt = chargeRate * time; if(isContested || reg is null) { amt = 0.f; } else if(reg.TradeMask & owner.TradeMask.value == 0) { if(reg.isTradableRegion(owner)) amt *= SUPPLY_TRADE_RATE; else amt *= SUPPLY_UNOWNED_RATE; } if(amt > 0) { ship.Supply = min(ship.MaxSupply, ship.Supply + amt); barDelta = true; } } //Supply effectiveness float sup = ship.Supply / ship.MaxSupply; if(sup < SUPPLY_THRESHOLD) fleetEffectiveness *= SUPPLY_EFFICIENCY + sqrt(sup/SUPPLY_THRESHOLD) * (1.f - SUPPLY_EFFICIENCY); } else { fleetEffectiveness *= SUPPLY_EFFICIENCY; } //Efficiency decrease due to debt float debtFactor = ship.owner.DebtFactor; if(debtFactor > 1.f) fleetEffectiveness *= pow(0.5f, debtFactor-1.f); fleetEffectiveness *= owner.FleetEfficiencyFactor; ship.setFleetEffectiveness(fleetEffectiveness); } updateAccel(ship); float effectiveness = shipEffectiveness; float prevEffectiveness = ship.blueprint.shipEffectiveness; //Deal with fleet effectiveness if(ship.hasLeaderAI) { effectiveness *= ship.getFleetEffectiveness(); ship.blueprint.shipEffectiveness = effectiveness; ship.updateFleetStrength(); } else { Object@ leader = ship.Leader; if(leader !is null) effectiveness *= leader.getFleetEffectiveness(); else effectiveness *= SUPPLY_EFFICIENCY; ship.blueprint.shipEffectiveness = effectiveness; } if(prevEffectiveness != ship.blueprint.shipEffectiveness) ship.blueprint.delta = true; if(suppression > 0.f) { //Apply suppression before recovery, or small suppression will never do anything effectiveness /= 1.f + suppression; suppression -= (1.f + suppression) * SUPPRESSION_REGEN * time; if(suppression < 0.f) suppression = 0.f; } if(onFire && time > 0) { double fireDamage = ship.blueprint.design.size * FIRE_DPS * time * owner.FireDamageTakenFactor; internalDamage(ship, fireDamage); if(effectiveness > 0 && randomd() < pow(EXTINGUISH_CHANCE, 1.0 / (time * effectiveness))) onFire = false; } //Clear kill credits after short spans of time if(killCredit !is null && !ship.inCombat) { @killCredit = null; @lastHitBy = null; } //Check if we can retrofit if(queuedRetrofit !is null && !isContested) { retrofit(ship, queuedRetrofit); @queuedRetrofit = null; } @cachedLeader = ship.Leader; } double tick(Ship& ship, double time) { auto@ bp = ship.blueprint; if(bp.statusID != bpStatusID) updateStats(ship); bool inCombat = ship.inCombat; //Keep a timer for some occasional checks timer += float(time); if(timer >= 1.f) { occasional_tick(ship, timer); timer = 0.f; } double delay = 0.2; double d = 0.2; if(inCombat) { bpTimer += time; if(bpTimer > 0.2f) { d = bp.tick(ship, bpTimer); bpTimer = 0.f; } } else { bpTimer += time; if(bpTimer >= 1.f) { d = bp.tick(ship, bpTimer); bpTimer = 0.f; } } if(!ship.hasSupportAI) { if(ship.hasLeaderAI) { ship.orderTick(time); ship.leaderTick(time); } if(ship.hasAbilities) ship.abilityTick(time); if(ship.hasStatuses) ship.statusTick(time); if(ship.hasConstruction) ship.constructionTick(time); } if(d < delay) delay = d; d = ship.moverTick(time); if(d < delay) delay = d; if(ship.Shield < ship.MaxShield) { ship.Shield = min(ship.Shield + shieldRegen * time, ship.MaxShield); shieldDelta = true; } //Repair out of combat double damage = bp.design.totalHP - (bp.currentHP + bp.removedHP); if(currentRepair > 0.f && (damage > 0.f || wreckage > 0.f)) { double repairFact = 1.0; bool inCombat = ship.inCombat; if(inCombat) { repairFact *= COMBAT_REPAIR_MOD; repairFact *= min(bp.shipEffectiveness, 1.0); } if(repairFact != 0) { double repairAmt = currentRepair * repairFact * time; double repairCost = currentRepairCost * repairFact * time; if(inCombat) { if(repairCost < 0) { repairAmt = 0; } else if(cachedLeader !is null) { Ship@ shipLeader = cast(cachedLeader); if(shipLeader !is null) { if(shipLeader.Supply < repairCost) repairAmt = 0.0; else shipLeader.consumeSupply(repairCost); } } else { if(ship.Supply < repairCost) repairAmt = 0.0; else consumeSupply(ship, repairCost); } } if(repairAmt != 0) { if(wreckage > 0.f) { double repWreckage = repairAmt * wreckage / (wreckage + damage); repairAmt -= repWreckage; wreckage -= repWreckage; } bp.repair(ship, repairAmt); } } } else { bp.repairingHex.x = -1; bp.repairingHex.y = -1; needRepair = false; } return delay; } void internalDamage(Ship& ship, double amount) { Blueprint@ bp = ship.blueprint; const Design@ dsg = bp.design; vec2i gridSize = dsg.hull.gridSize; vec2i base = vec2i(randomi(0, gridSize.x-1), randomi(0, gridSize.y-1)); for(int x = 0; x < gridSize.x; ++x) { for(int y = 0; y < gridSize.y; ++y) { vec2u pos = vec2u((base.x + x) % gridSize.x, (base.y + y) % gridSize.y); auto status = bp.getHexStatus(pos.x,pos.y); if(status is null || status.hp == 0) continue; DamageEvent evt; evt.damage = amount; bp.damage(ship, evt, pos); needRepair = true; return; } } } void recordDamage(Ship& ship, Object@ source) { if(source !is null) { if(lastHitBy !is source && ship.hasLeaderAI) { //Order a random support to block, and another to attack uint cnt = ship.supportCount; if(cnt > 0) { uint ind = randomi(0,cnt-1); Object@ sup = ship.supportShip[ind]; if(sup !is null) sup.supportInterfere(lastHitBy, ship); if(cnt > 1) { @sup = ship.supportShip[ind+1]; if(sup !is null) sup.supportAttack(lastHitBy); } } } @lastHitBy = source; @killCredit = source.owner; } } void damage(Ship& ship, DamageEvent& evt, double position, const vec2d& direction) { //Score kills to the last aggressor double prevShield = ship.Shield; if(evt.obj !is null) { if(lastHitBy !is evt.obj && ship.hasLeaderAI) { //Order a random support to block, and another to attack uint cnt = ship.supportCount; if(cnt > 0) { uint ind = randomi(0,cnt-1); Object@ sup = ship.supportShip[ind]; if(sup !is null) sup.supportInterfere(lastHitBy, ship); if(cnt > 1) { @sup = ship.supportShip[ind+1]; if(sup !is null) sup.supportAttack(lastHitBy); } } } @lastHitBy = evt.obj; @killCredit = evt.obj.owner; } ship.engaged = true; ship.blueprint.damage(ship, evt, direction); needRepair = true; if(prevShield != ship.Shield) shieldDelta = true; if(ship.blueprint.currentHP <= 0.01) { //This shouldn't be needed, but somehow it is ship.destroy(); } } void damageAllHexes(Ship& ship, double damage, Object@ source = null) { Blueprint@ bp = ship.blueprint; if(bp is null) return; const Design@ dsg = bp.design; if(dsg is null) return; DamageEvent evt; @evt.obj = ship; @evt.target = ship; evt.partiality = 1.0; for(uint i = 0, cnt = dsg.subsystemCount; i < cnt; ++i) { auto@ subsys = dsg.subsystems[i]; if(!subsys.has(HV_HP)) continue; for(uint n = 0, ncnt = subsys.hexCount; n < ncnt; ++n) { vec2u pos = subsys.hexagon(n); evt.damage = damage; evt.partiality = 1.0; bp.damageHex(ship, evt, pos, false); } } if(source !is null) recordDamage(ship, source); } void restoreShield(Ship& ship, double value) { double prevShield = ship.Shield; ship.Shield = clamp(ship.Shield + value, 0, ship.MaxShield); if(ship.Shield != prevShield) shieldDelta = true; } Empire@ getKillCredit() { return killCredit; } void syncInitial(const Ship& ship, Message& msg) { msg.writeSmall(ship.blueprint.design.hull.id); ship.blueprint.sendDetails(ship, msg); if(ship.hasLeaderAI) { msg.write1(); ship.writeLeaderAI(msg); } else { msg.write0(); ship.writeSupportAI(msg); } ship.writeMover(msg); if(ship.MaxEnergy > 0) { msg.write1(); msg << ship.MaxEnergy; msg.writeFixed(ship.Energy, 0.f, ship.MaxEnergy, 16); } else { msg.write0(); } if(ship.MaxSupply > 0) { msg.write1(); msg << ship.MaxSupply; msg.writeFixed(ship.Supply, 0.f, ship.MaxSupply, 16); } else { msg.write0(); } if(ship.MaxShield > 0) { msg.write1(); msg << ship.MaxShield; msg.writeFixed(ship.Shield, 0.f, ship.MaxShield, 16); } else { msg.write0(); } if(ship.hasAbilities) { msg.write1(); ship.writeAbilities(msg); } else { msg.write0(); } if(ship.hasStatuses) { msg.write1(); ship.writeStatuses(msg); } else { msg.write0(); } if(ship.hasCargo) { msg.write1(); ship.writeCargo(msg); } else { msg.write0(); } if(ship.hasConstruction) { msg.write1(); ship.writeConstruction(msg); } else { msg.write0(); } if(ship.hasOrbit) { msg.write1(); ship.writeOrbit(msg); } else { msg.write0(); } } void retrofit(Ship& ship, const Design@ newDesign) { const Design@ prevDesign = ship.blueprint.design; ship.blueprint.retrofit(ship, newDesign); cacheStats(ship); ship.Energy = min(ship.Energy, ship.MaxEnergy); if(ship.hasAbilities) ship.initAbilities(ship.blueprint.design); if(newDesign.base() !is prevDesign.base()) { if(ship.hasLeaderAI) { ship.recalculateLevels(prevDesign.size, newDesign.size); } else if(ship.hasSupportAI) { Object@ leader = ship.Leader; if(leader !is null) leader.postSupportRetrofit(ship, prevDesign, newDesign); } } ship.Supply = min(ship.Supply, ship.MaxSupply); ship.Shield = min(ship.Shield, ship.MaxShield); barDelta = true; } void syncDetailed(const Ship& ship, Message& msg) { ship.writeMover(msg); if(ship.hasLeaderAI) ship.writeLeaderAI(msg); else ship.writeSupportAI(msg); ship.blueprint.sendDetails(ship, msg); msg << ship.Energy; msg << ship.MaxEnergy; msg << ship.Supply; msg << ship.MaxSupply; msg << ship.Shield; msg << ship.MaxShield; msg.writeBit(ship.isFTLing); msg.writeBit(ship.inCombat); if(ship.hasAbilities) ship.writeAbilities(msg); if(ship.hasStatuses) ship.writeStatuses(msg); if(ship.hasCargo) { msg.write1(); ship.writeCargo(msg); } else { msg.write0(); } if(ship.hasOrbit) { msg.write1(); ship.writeOrbit(msg); } else { msg.write0(); } if(ship.hasConstruction) { msg.write1(); ship.writeConstruction(msg); } else { msg.write0(); } } bool prevFTL = false, prevCombat = false; bool syncDelta(const Ship& ship, Message& msg) { bool used = false; if(ship.writeMoverDelta(msg)) used = true; else msg.write0(); if(ship.blueprint.sendDelta(ship, msg)) used = true; else msg.write0(); msg.writeBit(shieldDelta); if(shieldDelta) { used = true; shieldDelta = false; msg.writeFixed(ship.Shield, 0.f, ship.MaxShield, 16); } if(ship.hasLeaderAI) { if(ship.writeLeaderAIDelta(msg)) used = true; else msg.write0(); } else { if(ship.writeSupportAIDelta(msg)) used = true; else msg.write0(); } if(ship.hasAbilities) { if(ship.writeAbilityDelta(msg)) used = true; else msg.write0(); } if(ship.hasStatuses) { if(ship.writeStatusDelta(msg)) used = true; else msg.write0(); } if(ship.hasLeaderAI) { if(ship.hasCargo) { if(ship.writeCargoDelta(msg)) used = true; else msg.write0(); } else { msg.write0(); } } if(barDelta || prevFTL != ship.isFTLing || prevCombat != ship.inCombat) { msg.write1(); used = true; msg.writeBit(ship.Energy > 0); if(ship.Energy > 0) msg << ship.Energy; msg.writeBit(ship.Supply > 0); if(ship.Supply > 0) msg << ship.Supply; msg.writeBit(ship.isFTLing); msg.writeBit(ship.inCombat); barDelta = false; prevFTL = ship.isFTLing; prevCombat = ship.inCombat; } else { msg.write0(); } if(ship.hasOrbit) { if(ship.writeOrbitDelta(msg)) used = true; else msg.write0(); } else { msg.write0(); } if(ship.hasLeaderAI && ship.hasConstruction) { if(ship.writeConstructionDelta(msg)) used = true; else msg.write0(); } else { msg.write0(); } return used; } }; ",12121,False,2320.3360765507186,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.effects { import flash.events.Event; import flash.events.EventDispatcher; import mx.core.FlexVersion; import mx.core.IFlexDisplayObject; import mx.core.mx_internal; import mx.effects.effectClasses.AddRemoveEffectTargetFilter; import mx.effects.effectClasses.HideShowEffectTargetFilter; import mx.effects.effectClasses.PropertyChanges; import mx.events.EffectEvent; import mx.managers.LayoutManager; import mx.styles.IStyleClient; import mx.utils.NameUtil; use namespace mx_internal; /** * Dispatched when one of the effect's instances finishes playing, * either when the instance finishes playing or when the effect * is interrupted by a call to the end() method. * * @eventType mx.events.EffectEvent.EFFECT_END * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""effectEnd"", type=""mx.events.EffectEvent"")] /** * Dispatched when the effect has been stopped, * which only occurs when the effect is * interrupted by a call to the stop() method. * The EFFECT_END event is also dispatched to indicate that * the effect has ended. This extra event is sent first, as an * indicator to listeners that the effect did not reach its * end state. * * @eventType mx.events.EffectEvent.EFFECT_STOP * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""effectStop"", type=""mx.events.EffectEvent"")] /** * Dispatched when the effect starts playing. * * @eventType mx.events.EffectEvent.EFFECT_START * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""effectStart"", type=""mx.events.EffectEvent"")] /** * The Effect class is an abstract base class that defines the basic * functionality of all Flex effects. * The Effect class defines the base factory class for all effects. * The EffectInstance class defines the base class for all effect * instance subclasses. * *

You do not create an instance of the Effect class itself * in an application. * Instead, you create an instance of one of the subclasses, * such as Fade or WipeLeft.

* * @mxml * *

The Effect class defines the following properties, * which all of its subclasses inherit:

* *
 *  <mx:tagname
 *    Properties
 *    customFilter=""""
 *    duration=""500""
 *    filter=""""
 *    hideFocusRing=""false""
 *    perElementOffset=""0""
 *    repeatCount=""1""
 *    repeatDelay=""0""
 *    startDelay=""0""
 *    suspendBackgroundProcessing=""false|true""
 *    target=""effect target""
 *    targets=""array of effect targets""
 *     
 *    Events
 *    effectEnd=""No default""
 *    efectStart=""No default""
 *  />
 *  
* * @see mx.effects.EffectInstance * * @includeExample examples/SimpleEffectExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class Effect extends EventDispatcher implements IEffect { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * @private */ private static function mergeArrays(a1:Array, a2:Array):Array { if (a2) { for (var i2:int = 0; i2 < a2.length; i2++) { var addIt:Boolean = true; for (var i1:int = 0; i1 < a1.length; i1++) { if (a1[i1] == a2[i2]) { addIt = false; break; } } if (addIt) a1.push(a2[i2]); } } return a1; } /** * @private */ private static function stripUnchangedValues(propChanges:Array):Array { // Go through and remove any before/after values that are the same. for (var i:int = 0; i < propChanges.length; i++) { if (propChanges[i].stripUnchangedValues == false) continue; for (var prop:Object in propChanges[i].start) { if ((propChanges[i].start[prop] == propChanges[i].end[prop]) || (typeof(propChanges[i].start[prop]) == ""number"" && typeof(propChanges[i].end[prop])== ""number"" && isNaN(propChanges[i].start[prop]) && isNaN(propChanges[i].end[prop]))) { delete propChanges[i].start[prop]; delete propChanges[i].end[prop]; } } } return propChanges; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * *

Starting an effect is usually a three-step process:

* *
    *
  • Create an instance of the effect object * with the new operator.
  • *
  • Set properties on the effect object, * such as duration.
  • *
  • Call the play() method * or assign the effect to a trigger.
  • *
* * @param target The Object to animate with this effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Effect(target:Object = null) { super(); this.target = target; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- // Transitions will force the values animated by this effect to get set to // their final values, as specified in the end state, when the effect finishes. // This flag is set to true when the effect is being played by a transition, // but applying the values is still gated by the value of the // applyTransitionEndProperties flag, which is set on a per-Effect basis. mx_internal var applyEndValuesWhenDone:Boolean = false; // This property tracks whether the effect is playing in interruption mode. // Normally, effects pick up starting values (when not provided explicitly) // from the current values of the target objects. But when playing in interruption // mode, the effect should get its starting values from the propertyChanges // array instead. private var _transitionInterruption:Boolean = false; mx_internal function get transitionInterruption():Boolean { return _transitionInterruption; } mx_internal function set transitionInterruption(value:Boolean):void { _transitionInterruption = value; } // This is new behavior for the Flex4 effects; previously, we would not // set the end-state values automatically. Because of this switch, the // default value is hinged on a compatibility check, so that applications // can choose to have the older behavior instead. /** * This flag controls whether the effect, when run in a transition, * automatically applies the property values according to the end * state, as opposed to leaving values as set by the effect itself. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var applyTransitionEndProperties:Boolean = (FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0) ? false : true; /** * @private */ private var _instances:Array /* of EffectInstance */ = []; /** * @private */ private var _callValidateNow:Boolean = false; /** * @private */ private var isPaused:Boolean = false; /** * @private */ mx_internal var filterObject:EffectTargetFilter; /** * @private * Used in applyValueToTarget() */ mx_internal var applyActualDimensions:Boolean = true; /** * @private * Holds the init object passed in by the Transition. */ mx_internal var propertyChangesArray:Array; /** * @private * Track the property set in the play() function */ mx_internal var playReversed:Boolean; private var effectStopped:Boolean; /** * @private * Pointer back to the CompositeEffect that created this instance. * Value is null if we are not the child of a CompositeEffect */ mx_internal var parentCompositeEffect:Effect; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // className //---------------------------------- /** * @copy mx.effects.IEffect#className * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get className():String { return NameUtil.getUnqualifiedClassName(this); } //---------------------------------- // customFilter //---------------------------------- /** * @private * Storage for the customFilter property. */ private var _customFilter:EffectTargetFilter; /** * @copy mx.effects.IEffect#customFilter * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get customFilter():EffectTargetFilter { return _customFilter; } /** * @private */ public function set customFilter(value:EffectTargetFilter):void { _customFilter = value; filterObject = value; } //---------------------------------- // duration //---------------------------------- /** * @private * Storage for the duration property. */ private var _duration:Number = 500; /** * @private */ mx_internal var durationExplicitlySet:Boolean = false; [Inspectable(category=""General"", defaultValue=""500"", minValue=""0.0"")] /** * @copy mx.effects.IEffect#duration * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get duration():Number { if (!durationExplicitlySet && parentCompositeEffect) { return parentCompositeEffect.duration; } else { return _duration; } } /** * @private */ public function set duration(value:Number):void { durationExplicitlySet = true; _duration = value; } //---------------------------------- // effectTargetHost //---------------------------------- /** * @private * Storage for the effectTargetHost property. */ private var _effectTargetHost:IEffectTargetHost; /** * @copy mx.effects.IEffect#effectTargetHost * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get effectTargetHost():IEffectTargetHost { return _effectTargetHost; } /** * @private */ public function set effectTargetHost(value:IEffectTargetHost):void { _effectTargetHost = value; } //---------------------------------- // endValuesCaptured //---------------------------------- /** * A flag containing true if the end values * of an effect have already been determined, * or false if they should be acquired from the * current properties of the effect targets when the effect runs. * This property is required by data effects because the sequence * of setting up the data effects, such as DefaultListEffect * and DefaultTileListEffect, is more complicated than for * normal effects. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var endValuesCaptured:Boolean = false; //---------------------------------- // filter //---------------------------------- /** * @private * Storage for the filter property. */ private var _filter:String; [Inspectable(category=""General"", enumeration=""add,remove,show,hide,move,resize,addItem,removeItem,replacedItem,replacementItem,none"", defaultValue=""none"")] /** * @copy mx.effects.IEffect#filter * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get filter():String { return _filter; } /** * @private */ public function set filter(value:String):void { if (!customFilter) { _filter = value; switch (value) { case ""add"": case ""remove"": { filterObject = new AddRemoveEffectTargetFilter(); AddRemoveEffectTargetFilter(filterObject).add = (value == ""add""); break; } case ""hide"": case ""show"": { filterObject = new HideShowEffectTargetFilter(); HideShowEffectTargetFilter(filterObject).show = (value == ""show""); break; } case ""move"": { filterObject = new EffectTargetFilter(); filterObject.filterProperties = [ ""x"", ""y"" ]; break; } case ""resize"": { filterObject = new EffectTargetFilter(); filterObject.filterProperties = [ ""width"", ""height"" ]; break; } case ""addItem"": { filterObject = new EffectTargetFilter(); filterObject.requiredSemantics = {added:true}; break; } case ""removeItem"": { filterObject = new EffectTargetFilter(); filterObject.requiredSemantics = {removed:true}; break; } case ""replacedItem"": { filterObject = new EffectTargetFilter(); filterObject.requiredSemantics = {replaced:true}; break; } case ""replacementItem"": { filterObject = new EffectTargetFilter(); filterObject.requiredSemantics = {replacement:true}; break; } default: { filterObject = null; break; } } } } //---------------------------------- // hideFocusRing //---------------------------------- /** * @private * Storage for the hideFocusRing property. */ private var _hideFocusRing:Boolean = false; /** * @copy mx.effects.IEffect#hideFocusRing * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get hideFocusRing():Boolean { return _hideFocusRing; } /** * @private */ public function set hideFocusRing(value:Boolean):void { _hideFocusRing = value; } //---------------------------------- // instanceClass //---------------------------------- /** * An object of type Class that specifies the effect * instance class class for this effect class. * *

All subclasses of the Effect class must set this property * in their constructor.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var instanceClass:Class = IEffectInstance; //---------------------------------- // isPlaying //---------------------------------- /** * @copy mx.effects.IEffect#isPlaying * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get isPlaying():Boolean { return _instances && _instances.length > 0; } //---------------------------------- // perElementOffset //---------------------------------- /** * @private * Storage for the perElementOffset property. */ private var _perElementOffset:Number = 0; [Inspectable(defaultValue=""0"", category=""General"", verbose=""0"", minValue=""0.0"")] /** * @copy mx.effects.IEffect#perElementOffset * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get perElementOffset():Number { return _perElementOffset; } /** * @private */ public function set perElementOffset(value:Number):void { _perElementOffset = value; } //---------------------------------- // relevantProperties //---------------------------------- /** * @private * Storage for the relevantProperties property. */ private var _relevantProperties:Array /* of String */; /** * @copy mx.effects.IEffect#relevantProperties * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get relevantProperties():Array /* of String */ { if (_relevantProperties) return _relevantProperties; else return getAffectedProperties(); } /** * @private */ public function set relevantProperties(value:Array /* of String */):void { _relevantProperties = value; } //---------------------------------- // relevantStyles //---------------------------------- /** * @private * Storage for the relevantStyles property. */ private var _relevantStyles:Array /* of String */ = []; /** * @copy mx.effects.IEffect#relevantStyles * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get relevantStyles():Array /* of String */ { return _relevantStyles; } /** * @private */ public function set relevantStyles(value:Array /* of String */):void { _relevantStyles = value; } //---------------------------------- // repeatCount //---------------------------------- [Inspectable(category=""General"", defaultValue=""1"", minValue=""0"")] /** * Number of times to repeat the effect. * Possible values are any integer greater than or equal to 0. * A value of 1 means to play the effect once. * A value of 0 means to play the effect indefinitely * until stopped by a call to the end() method. * * @default 1 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var repeatCount:int = 1; //---------------------------------- // repeatDelay //---------------------------------- [Inspectable(category=""General"", defaultValue=""0"", minValue=""0"")] /** * Amount of time, in milliseconds, to wait before repeating the effect. * Possible values are any integer greater than or equal to 0. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var repeatDelay:int = 0; //---------------------------------- // startDelay //---------------------------------- [Inspectable(category=""General"", defaultValue=""0"", minValue=""0"")] /** * Amount of time, in milliseconds, to wait before starting the effect. * Possible values are any int greater than or equal to 0. * If the effect is repeated by using the repeatCount * property, the startDelay is only applied * to the first time the effect is played. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var startDelay:int = 0; //---------------------------------- // suspendBackgroundProcessing //---------------------------------- /** * If true, blocks all background processing * while the effect is playing. * Background processing includes measurement, layout, and * processing responses that have arrived from the server. * The default value is false. * *

You are encouraged to set this property to * true in most cases, because it improves * the performance of the application. * However, the property should be set to false * if either of the following is true:

*
    *
  • User input can arrive while the effect is playing, * and the application must respond to the user input * before the effect finishes playing.
  • *
  • A response can arrive from the server while the effect * is playing, and the application must process the response * while the effect is still playing.
  • *
* * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var suspendBackgroundProcessing:Boolean = false; //---------------------------------- // target //---------------------------------- /** * @copy mx.effects.IEffect#target * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get target():Object { if (_targets.length > 0) return _targets[0]; else return null; } /** * @private */ public function set target(value:Object):void { _targets.splice(0); if (value) _targets[0] = value; } //---------------------------------- // targets //---------------------------------- /** * @private * Storage for the targets property. */ private var _targets:Array = []; [Inspectable(arrayType=""Object"")] [ArrayElementType(""Object"")] /** * @copy mx.effects.IEffect#targets * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get targets():Array { return _targets; } /** * @private */ public function set targets(value:Array):void { // Strip out null values. // Binding will trigger again when the null targets are created. var n:int = value.length; for (var i:int = n - 1; i >= 0; i--) { if (value[i] == null) value.splice(i,1); } _targets = value; } //---------------------------------- // triggerEvent //---------------------------------- /** * @private * Storage for the triggerEvent property. */ private var _triggerEvent:Event; /** * @copy mx.effects.IEffect#triggerEvent * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get triggerEvent():Event { return _triggerEvent; } /** * @private */ public function set triggerEvent(value:Event):void { _triggerEvent = value; } //---------------------------------- // playheadTime //---------------------------------- /** * @private * Backing storage for the playheadTime property. Note that this * value is just a backup, used if the effect is not currently running. * A running effect will query its effect instance for the value * instead. */ private var _playheadTime:Number = 0; [Inspectable(minValue=""0.0"")] /** * Current time position of the effect. * This property has a value between 0 and the total duration, * which includes the Effect's startDelay, * repeatCount, and repeatDelay. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get playheadTime():Number { for (var i:int = 0; i < _instances.length; i++) { if (_instances[i]) return IEffectInstance(_instances[i]).playheadTime; } // Effect isn't running: return the cached value return _playheadTime; } public function set playheadTime(value:Number):void { // If the effect is not yet playing, it should still be possible // to seek into it. playing and then pausing it provides that // capability // TODO (chaase): Need better overall mechanism to seek into a // non-playing effect. The internals of seeking in Animation // are complicated and don't end up giving us the behavior we // want, especially for successive seeks. var started:Boolean = false; if (_instances.length == 0) { play(); started = true; } for (var i:int = 0; i < _instances.length; i++) { if (_instances[i]) EffectInstance(_instances[i]).playheadTime = value; } if (started) pause(); _playheadTime = value; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @copy mx.effects.IEffect#getAffectedProperties() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getAffectedProperties():Array /* of String */ { // Every subclass should override this method. return []; } /** * @copy mx.effects.IEffect#createInstances() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function createInstances(targets:Array = null):Array /* of EffectInstance */ { if (!targets) targets = this.targets; var newInstances:Array = []; // Multiple target support var n:int = targets.length; var offsetDelay:Number = 0; for (var i:int = 0; i < n; i++) { var newInstance:IEffectInstance = createInstance(targets[i]); if (newInstance) { newInstance.startDelay += offsetDelay; offsetDelay += perElementOffset; newInstances.push(newInstance); } } triggerEvent = null; return newInstances; } /** * @copy mx.effects.IEffect#createInstance() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function createInstance(target:Object = null):IEffectInstance { if (!target) target = this.target; var newInstance:IEffectInstance = null; var props:PropertyChanges = null; var create:Boolean = true; var setPropsArray:Boolean = false; if (propertyChangesArray) { setPropsArray = true; create = filterInstance(propertyChangesArray, target); } if (create) { newInstance = IEffectInstance(new instanceClass(target)); initInstance(newInstance); if (setPropsArray) { var n:int = propertyChangesArray.length; for (var i:int = 0; i < n; i++) { if (propertyChangesArray[i].target == target) { newInstance.propertyChanges = propertyChangesArray[i]; } } } EventDispatcher(newInstance).addEventListener(EffectEvent.EFFECT_START, effectStartHandler); EventDispatcher(newInstance).addEventListener(EffectEvent.EFFECT_STOP, effectStopHandler); EventDispatcher(newInstance).addEventListener(EffectEvent.EFFECT_END, effectEndHandler); _instances.push(newInstance); if (triggerEvent) newInstance.initEffect(triggerEvent); } return newInstance; } /** * Copies properties of the effect to the effect instance. * *

Flex calls this method from the Effect.createInstance() * method; you do not have to call it yourself.

* *

When you create a custom effect, override this method to * copy properties from the Effect class to the effect instance class. * In your override, call super.initInstance().

* * @param EffectInstance The effect instance to initialize. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function initInstance(instance:IEffectInstance):void { instance.duration = duration; Object(instance).durationExplicitlySet = durationExplicitlySet; instance.effect = this; instance.effectTargetHost = effectTargetHost; instance.hideFocusRing = hideFocusRing; instance.repeatCount = repeatCount; instance.repeatDelay = repeatDelay; instance.startDelay = startDelay; instance.suspendBackgroundProcessing = suspendBackgroundProcessing; } /** * @copy mx.effects.IEffect#deleteInstance() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function deleteInstance(instance:IEffectInstance):void { EventDispatcher(instance).removeEventListener( EffectEvent.EFFECT_START, effectStartHandler); EventDispatcher(instance).removeEventListener( EffectEvent.EFFECT_STOP, effectStopHandler); EventDispatcher(instance).removeEventListener( EffectEvent.EFFECT_END, effectEndHandler); var n:int = _instances.length; for (var i:int = 0; i < n; i++) { if (_instances[i] === instance) _instances.splice(i, 1); } } /** * @copy mx.effects.IEffect#play() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function play(targets:Array = null, playReversedFromEnd:Boolean = false): Array /* of EffectInstance */ { effectStopped = false; isPaused = false; playReversed = playReversedFromEnd; // If we have a propertyChangesArray, capture the current values // if they haven't been captured already, strip out any unchanged // values, then apply the start values. if (targets == null && propertyChangesArray != null) { if (_callValidateNow) LayoutManager.getInstance().validateNow(); if (!endValuesCaptured) propertyChangesArray = captureValues(propertyChangesArray, false); propertyChangesArray = stripUnchangedValues(propertyChangesArray); applyStartValues(propertyChangesArray, this.targets); if (playReversedFromEnd) { for (var j:int = 0; j < propertyChangesArray.length; ++j) { var tmpStart:Object = propertyChangesArray[j].start; propertyChangesArray[j].start = propertyChangesArray[j].end; propertyChangesArray[j].end = tmpStart; } } // Revalidate after applying the start values, to get everything // back the way it should be before starting the animation LayoutManager.getInstance().validateNow(); applyEndValuesWhenDone = true; } var newInstances:Array = createInstances(targets); var n:int = newInstances.length; for (var i:int = 0; i < n; i++) { var newInstance:IEffectInstance = IEffectInstance(newInstances[i]); Object(newInstance).playReversed = playReversedFromEnd; newInstance.startEffect(); } return newInstances; } /** * @copy mx.effects.IEffect#pause() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function pause():void { if (isPlaying && !isPaused) { isPaused = true; var n:int = _instances.length; for (var i:int = 0; i < n; i++) { IEffectInstance(_instances[i]).pause(); } } } /** * @copy mx.effects.IEffect#stop() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function stop():void { var n:int = _instances.length - 1; for (var i:int = n; i >= 0; i--) { var instance:IEffectInstance = IEffectInstance(_instances[i]); if (instance) instance.stop(); } } /** * @copy mx.effects.IEffect#resume() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function resume():void { if (isPlaying && isPaused) { isPaused = false; var n:int = _instances.length; for (var i:int = 0; i < n; i++) { IEffectInstance(_instances[i]).resume(); } } } /** * @copy mx.effects.IEffect#reverse() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function reverse():void { if (isPlaying) { var n:int = _instances.length; for (var i:int = 0; i < n; i++) { IEffectInstance(_instances[i]).reverse(); } } } /** * @copy mx.effects.IEffect#end() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function end(effectInstance:IEffectInstance = null):void { if (effectInstance) { effectInstance.end(); } else { var n:int = _instances.length; for (var i:int = n - 1; i >= 0; i--) { var instance:IEffectInstance = IEffectInstance(_instances[i]); if (instance) instance.end(); } } } /** * Determines the logic for filtering out an effect instance. * The CompositeEffect class overrides this method. * * @param propChanges The properties modified by the effect. * * @param targ The effect target. * * @return Returns true if the effect instance should play. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function filterInstance(propChanges:Array, target:Object):Boolean { if (filterObject) return filterObject.filterInstance(propChanges, effectTargetHost, target); return true; } /** * @copy mx.effects.IEffect#captureStartValues() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function captureStartValues():void { if (targets.length > 0) { // Reset the PropertyChanges array by passing in 'null' propertyChangesArray = captureValues(null, true); _callValidateNow = true; } endValuesCaptured = false; } /** * @copy mx.effects.IEffect#captureMoreStartValues() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function captureMoreStartValues(targets:Array):void { if (targets.length > 0) { // make temporary PropertyChangesArray var additionalPropertyChangesArray:Array = captureValues(null, true); propertyChangesArray = (propertyChangesArray != null) ? propertyChangesArray.concat(additionalPropertyChangesArray) : additionalPropertyChangesArray; } } /** * @copy mx.effects.IEffect#captureEndValues() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function captureEndValues():void { // captureValues will create propertyChangesArray if it does not // yet exist propertyChangesArray = captureValues(propertyChangesArray, false); endValuesCaptured = true; } /** * @private * Used internally to grab the values of the relevant properties */ mx_internal function captureValues(propChanges:Array, setStartValues:Boolean, targetsToCapture:Array = null):Array { var n:int; var i:int; if (!propChanges) { propChanges = []; // Create a new PropertyChanges object for the sum of all targets. n = targets.length; for (i = 0; i < n; i++) propChanges.push(new PropertyChanges(targets[i])); } // Merge Effect.filterProperties and filterObject.filterProperties var effectProps:Array = !filterObject ? relevantProperties : mergeArrays(relevantProperties, filterObject.filterProperties); var valueMap:Object; var target:Object; var m:int; var j:int; // For each target, grab the property's value // and put it into the propChanges Array. // Walk the targets. if (effectProps && effectProps.length > 0) { n = propChanges.length; for (i = 0; i < n; i++) { target = propChanges[i].target; if (targetsToCapture == null || targetsToCapture.length == 0 || targetsToCapture.indexOf(target) >= 0) { valueMap = setStartValues ? propChanges[i].start : propChanges[i].end; // Walk the properties in the target m = effectProps.length; for (j = 0; j < m; j++) { // Don't clobber values already set if (valueMap[effectProps[j]] === undefined) { valueMap[effectProps[j]] = getValueFromTarget(target,effectProps[j]); } } } } } var styles:Array = !filterObject ? relevantStyles : mergeArrays(relevantStyles, filterObject.filterStyles); if (styles && styles.length > 0) { n = propChanges.length; for (i = 0; i < n; i++) { target = propChanges[i].target; if (targetsToCapture == null || targetsToCapture.length == 0 || targetsToCapture.indexOf(target) >= 0) { if (!(target is IStyleClient)) continue; valueMap = setStartValues ? propChanges[i].start : propChanges[i].end; // Walk the properties in the target. m = styles.length; for (j = 0; j < m; j++) { // Don't clobber values set by relevantProperties if (valueMap[styles[j]] === undefined) { var value:* = target.getStyle(styles[j]); valueMap[styles[j]] = value; } } } } } return propChanges; } /** * Called by the captureStartValues() method to get the value * of a property from the target. * This function should only be called internally * by the effects framework. * The default behavior is to simply return target[property]. * Effect developers can override this function * if you need a different behavior. * * @param target The effect target. * * @param property The target property. * * @return The value of the target property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function getValueFromTarget(target:Object, property:String):* { if (property in target) return target[property]; return undefined; } /** * @private * Applies the start values found in the array of PropertyChanges * to the relevant targets. */ mx_internal function applyStartValues(propChanges:Array, targets:Array):void { var effectProps:Array = relevantProperties; var n:int = propChanges.length; for (var i:int = 0; i < n; i++) { var m:int; var j:int; var target:Object = propChanges[i].target; var apply:Boolean = false; m = targets.length; for (j = 0; j < m; j++) { if (targets[j] == target) { apply = filterInstance(propChanges, target); break; } } if (apply) { // Walk the properties in the target m = effectProps.length; for (j = 0; j < m; j++) { var propName:String = effectProps[j]; var startVal:* = propChanges[i].start[propName]; var endVal:* = propChanges[i].end[propName]; if (propName in propChanges[i].start && endVal != startVal && (!(startVal is Number) || !(isNaN(endVal) && isNaN(startVal)))) { applyValueToTarget(target, effectProps[j], propChanges[i].start[effectProps[j]], propChanges[i].start); } } // Walk the styles in the target m = relevantStyles.length; for (j = 0; j < m; j++) { var styleName:String = relevantStyles[j]; var startStyle:* = propChanges[i].start[styleName]; var endStyle:* = propChanges[i].end[styleName]; if (styleName in propChanges[i].start && endStyle != startStyle && (!(startStyle is Number) || !(isNaN(endStyle) && isNaN(startStyle))) && target is IStyleClient) { if (propChanges[i].end[relevantStyles[j]] !== undefined) target.setStyle(relevantStyles[j], propChanges[i].start[relevantStyles[j]]); else target.clearStyle(relevantStyles[j]); } } } } } /** * @private * Applies the start values found in the array of PropertyChanges * to the relevant targets. */ mx_internal function applyEndValues(propChanges:Array, targets:Array):void { // For now, only new Flex4 effects will apply end values when transitions // are over, to preserve the previous behavior of Flex3 effects if (!applyTransitionEndProperties) return; var effectProps:Array = relevantProperties; var n:int = propChanges.length; for (var i:int = 0; i < n; i++) { var m:int; var j:int; var target:Object = propChanges[i].target; var apply:Boolean = false; m = targets.length; for (j = 0; j < m; j++) { if (targets[j] == target) { apply = filterInstance(propChanges, target); break; } } if (apply) { // Walk the properties in the target m = effectProps.length; for (j = 0; j < m; j++) { var propName:String = effectProps[j]; var startVal:* = propChanges[i].start[propName]; var endVal:* = propChanges[i].end[propName]; if (propName in propChanges[i].end && (!(endVal is Number) || !(isNaN(endVal) && isNaN(startVal)))) { applyValueToTarget(target, propName, propChanges[i].end[propName], propChanges[i].end); } } // Walk the styles in the target m = relevantStyles.length; for (j = 0; j < m; j++) { var styleName:String = relevantStyles[j]; var startStyle:* = propChanges[i].start[styleName]; var endStyle:* = propChanges[i].end[styleName]; if (styleName in propChanges[i].end && (!(endStyle is Number) || !(isNaN(endStyle) && isNaN(startStyle))) && target is IStyleClient) { if (propChanges[i].end[styleName] !== undefined) target.setStyle(styleName, propChanges[i].end[styleName]); else target.clearStyle(styleName); } } } } } /** * Used internally by the Effect infrastructure. * If captureStartValues() has been called, * then when Flex calls the play() method, it uses this function * to set the targets back to the starting state. * The default behavior is to take the value captured * using the getValueFromTarget() method * and set it directly on the target's property. For example:
     *  
     *  target[property] = value;
* *

Only override this method if you need to apply * the captured values in a different way. * Note that style properties of a target are set * using a different mechanism. * Use the relevantStyles property to specify * which style properties to capture and apply.

* * @param target The effect target. * * @param property The target property. * * @param value The value of the property. * * @param props Array of Objects, where each Array element contains a * start and end Object * for the properties that the effect is monitoring. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function applyValueToTarget(target:Object, property:String, value:*, props:Object):void { if (property in target) { // The ""property in target"" test only tells if the property exists // in the target, but does not distinguish between read-only and // read-write properties. Put a try/catch around the setter and // ignore any errors. try { if (applyActualDimensions && target is IFlexDisplayObject && property == ""height"") { target.setActualSize(target.width,value); } else if (applyActualDimensions && target is IFlexDisplayObject && property == ""width"") { target.setActualSize(value,target.height); } else { target[property] = value; } } catch(e:Error) { // Ignore errors } } } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * This method is called when the effect instance starts playing. * If you override this method, ensure that you call the super method. * * @param event An event object of type EffectEvent. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function effectStartHandler(event:EffectEvent):void { dispatchEvent(event); } /** * Called when an effect instance has stopped by a call * to the stop() method. * If you override this method, ensure that you call the super method. * * @param event An event object of type EffectEvent. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function effectStopHandler(event:EffectEvent):void { dispatchEvent(event); // We use this event to determine whether we should set final // state values in the ensuing endHandler() call effectStopped = true; } /** * Called when an effect instance has finished playing. * If you override this method, ensure that you call the super method. * * @param event An event object of type EffectEvent. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function effectEndHandler(event:EffectEvent):void { if (playReversed && propertyChangesArray != null) { for (var j:int = 0; j < propertyChangesArray.length; ++j) { var tmpStart:Object = propertyChangesArray[j].start; propertyChangesArray[j].start = propertyChangesArray[j].end; propertyChangesArray[j].end = tmpStart; } } var lastTime:Boolean = !_instances || _instances.length == 1; // Transitions should set the end values when done if (applyEndValuesWhenDone && !effectStopped && lastTime) applyEndValues(propertyChangesArray, targets); var instance:IEffectInstance = IEffectInstance(event.effectInstance); deleteInstance(instance); dispatchEvent(event); if (lastTime) { propertyChangesArray = null; applyEndValuesWhenDone = false; } } } } ",12394,True,2768.552614874432,median "------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . T A S K I N G . S T A G E S -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by Ada Core Technologies, Inc. -- -- -- ------------------------------------------------------------------------------ pragma Partition_Elaboration_Policy (Concurrent); -- This package only implements the concurrent elaboration policy. This pragma -- will enforce it (and detect conflicts with user specified policy). with Ada.Exceptions; with Ada.Unchecked_Deallocation; with System.Interrupt_Management; with System.Tasking.Debug; with System.Address_Image; with System.Task_Primitives; with System.Task_Primitives.Operations; with System.Tasking.Utilities; with System.Tasking.Queuing; with System.Tasking.Rendezvous; with System.OS_Primitives; with System.Secondary_Stack; with System.Restrictions; with System.Standard_Library; with System.Stack_Usage; with System.Storage_Elements; with System.Soft_Links; -- These are procedure pointers to non-tasking routines that use task -- specific data. In the absence of tasking, these routines refer to global -- data. In the presence of tasking, they must be replaced with pointers to -- task-specific versions. Also used for Create_TSD, Destroy_TSD, Get_Current -- _Excep, Finalize_Library_Objects, Task_Termination, Handler. with System.Tasking.Initialization; pragma Elaborate_All (System.Tasking.Initialization); -- This insures that tasking is initialized if any tasks are created package body System.Tasking.Stages is package STPO renames System.Task_Primitives.Operations; package SSL renames System.Soft_Links; package SSE renames System.Storage_Elements; use Ada.Exceptions; use Secondary_Stack; use Task_Primitives; use Task_Primitives.Operations; ----------------------- -- Local Subprograms -- ----------------------- procedure Free is new Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id); procedure Trace_Unhandled_Exception_In_Task (Self_Id : Task_Id); -- This procedure outputs the task specific message for exception -- tracing purposes. procedure Task_Wrapper (Self_ID : Task_Id); pragma Convention (C, Task_Wrapper); -- This is the procedure that is called by the GNULL from the new context -- when a task is created. It waits for activation and then calls the task -- body procedure. When the task body procedure completes, it terminates -- the task. -- -- The Task_Wrapper's address will be provided to the underlying threads -- library as the task entry point. Convention C is what makes most sense -- for that purpose (Export C would make the function globally visible, -- and affect the link name on which GDB depends). This will in addition -- trigger an automatic stack alignment suitable for GCC's assumptions if -- need be. -- ""Vulnerable_..."" in the procedure names below means they must be called -- with abort deferred. procedure Vulnerable_Complete_Task (Self_ID : Task_Id); -- Complete the calling task. This procedure must be called with -- abort deferred. It should only be called by Complete_Task and -- Finalize_Global_Tasks (for the environment task). procedure Vulnerable_Complete_Master (Self_ID : Task_Id); -- Complete the current master of the calling task. This procedure -- must be called with abort deferred. It should only be called by -- Vulnerable_Complete_Task and Complete_Master. procedure Vulnerable_Complete_Activation (Self_ID : Task_Id); -- Signal to Self_ID's activator that Self_ID has completed activation. -- This procedure must be called with abort deferred. procedure Abort_Dependents (Self_ID : Task_Id); -- Abort all the direct dependents of Self at its current master nesting -- level, plus all of their dependents, transitively. RTS_Lock should be -- locked by the caller. procedure Vulnerable_Free_Task (T : Task_Id); -- Recover all runtime system storage associated with the task T. This -- should only be called after T has terminated and will no longer be -- referenced. -- -- For tasks created by an allocator that fails, due to an exception, it is -- called from Expunge_Unactivated_Tasks. -- -- Different code is used at master completion, in Terminate_Dependents, -- due to a need for tighter synchronization with the master. ---------------------- -- Abort_Dependents -- ---------------------- procedure Abort_Dependents (Self_ID : Task_Id) is C : Task_Id; P : Task_Id; -- Each task C will take care of its own dependents, so there is no -- need to worry about them here. In fact, it would be wrong to abort -- indirect dependents here, because we can't distinguish between -- duplicate master ids. For example, suppose we have three nested -- task bodies T1,T2,T3. And suppose T1 also calls P which calls Q (and -- both P and Q are task masters). Q will have the same master id as -- Master_Of_Task of T3. Previous versions of this would abort T3 when -- Q calls Complete_Master, which was completely wrong. begin C := All_Tasks_List; while C /= null loop P := C.Common.Parent; if P = Self_ID then if C.Master_Of_Task = Self_ID.Master_Within then pragma Debug (Debug.Trace (Self_ID, ""Aborting"", 'X', C)); Utilities.Abort_One_Task (Self_ID, C); C.Dependents_Aborted := True; end if; end if; C := C.Common.All_Tasks_Link; end loop; Self_ID.Dependents_Aborted := True; end Abort_Dependents; ----------------- -- Abort_Tasks -- ----------------- procedure Abort_Tasks (Tasks : Task_List) is begin Utilities.Abort_Tasks (Tasks); end Abort_Tasks; -------------------- -- Activate_Tasks -- -------------------- -- Note that locks of activator and activated task are both locked here. -- This is necessary because C.Common.State and Self.Common.Wait_Count have -- to be synchronized. This is safe from deadlock because the activator is -- always created before the activated task. That satisfies our -- in-order-of-creation ATCB locking policy. -- At one point, we may also lock the parent, if the parent is different -- from the activator. That is also consistent with the lock ordering -- policy, since the activator cannot be created before the parent. -- Since we are holding both the activator's lock, and Task_Wrapper locks -- that before it does anything more than initialize the low-level ATCB -- components, it should be safe to wait to update the counts until we see -- that the thread creation is successful. -- If the thread creation fails, we do need to close the entries of the -- task. The first phase, of dequeuing calls, only requires locking the -- acceptor's ATCB, but the waking up of the callers requires locking the -- caller's ATCB. We cannot safely do this while we are holding other -- locks. Therefore, the queue-clearing operation is done in a separate -- pass over the activation chain. procedure Activate_Tasks (Chain_Access : Activation_Chain_Access) is Self_ID : constant Task_Id := STPO.Self; P : Task_Id; C : Task_Id; Next_C, Last_C : Task_Id; Activate_Prio : System.Any_Priority; Success : Boolean; All_Elaborated : Boolean := True; begin -- If pragma Detect_Blocking is active, then we must check whether this -- potentially blocking operation is called from a protected action. if System.Tasking.Detect_Blocking and then Self_ID.Common.Protected_Action_Nesting > 0 then raise Program_Error with ""potentially blocking operation""; end if; pragma Debug (Debug.Trace (Self_ID, ""Activate_Tasks"", 'C')); Initialization.Defer_Abort_Nestable (Self_ID); pragma Assert (Self_ID.Common.Wait_Count = 0); -- Lock RTS_Lock, to prevent activated tasks from racing ahead before -- we finish activating the chain. Lock_RTS; -- Check that all task bodies have been elaborated C := Chain_Access.T_ID; Last_C := null; while C /= null loop if C.Common.Elaborated /= null and then not C.Common.Elaborated.all then All_Elaborated := False; end if; -- Reverse the activation chain so that tasks are activated in the -- same order they're declared. Next_C := C.Common.Activation_Link; C.Common.Activation_Link := Last_C; Last_C := C; C := Next_C; end loop; Chain_Access.T_ID := Last_C; if not All_Elaborated then Unlock_RTS; Initialization.Undefer_Abort_Nestable (Self_ID); raise Program_Error with ""Some tasks have not been elaborated""; end if; -- Activate all the tasks in the chain. Creation of the thread of -- control was deferred until activation. So create it now. C := Chain_Access.T_ID; while C /= null loop if C.Common.State /= Terminated then pragma Assert (C.Common.State = Unactivated); P := C.Common.Parent; Write_Lock (P); Write_Lock (C); Activate_Prio := (if C.Common.Base_Priority < Get_Priority (Self_ID) then Get_Priority (Self_ID) else C.Common.Base_Priority); System.Task_Primitives.Operations.Create_Task (C, Task_Wrapper'Address, Parameters.Size_Type (C.Common.Compiler_Data.Pri_Stack_Info.Size), Activate_Prio, Success); -- There would be a race between the created task and the creator -- to do the following initialization, if we did not have a -- Lock/Unlock_RTS pair in the task wrapper to prevent it from -- racing ahead. if Success then C.Common.State := Activating; C.Awake_Count := 1; C.Alive_Count := 1; P.Awake_Count := P.Awake_Count + 1; P.Alive_Count := P.Alive_Count + 1; if P.Common.State = Master_Completion_Sleep and then C.Master_Of_Task = P.Master_Within then pragma Assert (Self_ID /= P); P.Common.Wait_Count := P.Common.Wait_Count + 1; end if; for J in System.Tasking.Debug.Known_Tasks'Range loop if System.Tasking.Debug.Known_Tasks (J) = null then System.Tasking.Debug.Known_Tasks (J) := C; C.Known_Tasks_Index := J; exit; end if; end loop; if Global_Task_Debug_Event_Set then Debug.Signal_Debug_Event (Debug.Debug_Event_Activating, C); end if; C.Common.State := Runnable; Unlock (C); Unlock (P); else -- No need to set Awake_Count, State, etc. here since the loop -- below will do that for any Unactivated tasks. Unlock (C); Unlock (P); Self_ID.Common.Activation_Failed := True; end if; end if; C := C.Common.Activation_Link; end loop; Unlock_RTS; -- Close the entries of any tasks that failed thread creation, and count -- those that have not finished activation. Write_Lock (Self_ID); Self_ID.Common.State := Activator_Sleep; C := Chain_Access.T_ID; while C /= null loop Write_Lock (C); if C.Common.State = Unactivated then C.Common.Activator := null; C.Common.State := Terminated; C.Callable := False; Utilities.Cancel_Queued_Entry_Calls (C); elsif C.Common.Activator /= null then Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1; end if; Unlock (C); P := C.Common.Activation_Link; C.Common.Activation_Link := null; C := P; end loop; -- Wait for the activated tasks to complete activation. It is -- unsafe to abort any of these tasks until the count goes to zero. loop exit when Self_ID.Common.Wait_Count = 0; Sleep (Self_ID, Activator_Sleep); end loop; Self_ID.Common.State := Runnable; Unlock (Self_ID); -- Remove the tasks from the chain Chain_Access.T_ID := null; Initialization.Undefer_Abort_Nestable (Self_ID); if Self_ID.Common.Activation_Failed then Self_ID.Common.Activation_Failed := False; raise Tasking_Error with ""Failure during activation""; end if; end Activate_Tasks; ------------------------- -- Complete_Activation -- ------------------------- procedure Complete_Activation is Self_ID : constant Task_Id := STPO.Self; begin Initialization.Defer_Abort_Nestable (Self_ID); Vulnerable_Complete_Activation (Self_ID); Initialization.Undefer_Abort_Nestable (Self_ID); -- ??? Why do we need to allow for nested deferral here? end Complete_Activation; --------------------- -- Complete_Master -- --------------------- procedure Complete_Master is Self_ID : constant Task_Id := STPO.Self; begin pragma Assert (Self_ID.Deferral_Level > 0 or else not System.Restrictions.Abort_Allowed); Vulnerable_Complete_Master (Self_ID); end Complete_Master; ------------------- -- Complete_Task -- ------------------- -- See comments on Vulnerable_Complete_Task for details procedure Complete_Task is Self_ID : constant Task_Id := STPO.Self; begin pragma Assert (Self_ID.Deferral_Level > 0 or else not System.Restrictions.Abort_Allowed); Vulnerable_Complete_Task (Self_ID); -- All of our dependents have terminated, never undefer abort again end Complete_Task; ----------------- -- Create_Task -- ----------------- -- Compiler interface only. Do not call from within the RTS. This must be -- called to create a new task. procedure Create_Task (Priority : Integer; Stack_Size : System.Parameters.Size_Type; Secondary_Stack_Size : System.Parameters.Size_Type; Task_Info : System.Task_Info.Task_Info_Type; CPU : Integer; Relative_Deadline : Ada.Real_Time.Time_Span; Domain : Dispatching_Domain_Access; Num_Entries : Task_Entry_Index; Master : Master_Level; State : Task_Procedure_Access; Discriminants : System.Address; Elaborated : Access_Boolean; Chain : in out Activation_Chain; Task_Image : String; Created_Task : out Task_Id) is T, P : Task_Id; Self_ID : constant Task_Id := STPO.Self; Success : Boolean; Base_Priority : System.Any_Priority; Len : Natural; Base_CPU : System.Multiprocessors.CPU_Range; use type System.Multiprocessors.CPU_Range; pragma Unreferenced (Relative_Deadline); -- EDF scheduling is not supported by any of the target platforms so -- this parameter is not passed any further. begin -- If Master is greater than the current master, it means that Master -- has already awaited its dependent tasks. This raises Program_Error, -- by 4.8(10.3/2). See AI-280. Ignore this check for foreign threads. if Self_ID.Master_Of_Task /= Foreign_Task_Level and then Master > Self_ID.Master_Within then raise Program_Error with ""create task after awaiting termination""; end if; -- If pragma Detect_Blocking is active must be checked whether this -- potentially blocking operation is called from a protected action. if System.Tasking.Detect_Blocking and then Self_ID.Common.Protected_Action_Nesting > 0 then raise Program_Error with ""potentially blocking operation""; end if; pragma Debug (Debug.Trace (Self_ID, ""Create_Task"", 'C')); Base_Priority := (if Priority = Unspecified_Priority then Self_ID.Common.Base_Priority else System.Any_Priority (Priority)); -- Legal values of CPU are the special Unspecified_CPU value which is -- inserted by the compiler for tasks without CPU aspect, and those in -- the range of CPU_Range but no greater than Number_Of_CPUs. Otherwise -- the task is defined to have failed, and it becomes a completed task -- (RM D.16(14/3)). if CPU /= Unspecified_CPU and then (CPU < Integer (System.Multiprocessors.CPU_Range'First) or else CPU > Integer (System.Multiprocessors.Number_Of_CPUs)) then raise Tasking_Error with ""CPU not in range""; -- Normal CPU affinity else -- When the application code says nothing about the task affinity -- (task without CPU aspect) then the compiler inserts the value -- Unspecified_CPU which indicates to the run-time library that -- the task will activate and execute on the same processor as its -- activating task if the activating task is assigned a processor -- (RM D.16(14/3)). Base_CPU := (if CPU = Unspecified_CPU then Self_ID.Common.Base_CPU else System.Multiprocessors.CPU_Range (CPU)); end if; -- Find parent P of new Task, via master level number. Independent -- tasks should have Parent = Environment_Task, and all tasks created -- by independent tasks are also independent. See, for example, -- s-interr.adb, where Interrupt_Manager does ""new Server_Task"". The -- access type is at library level, so the parent of the Server_Task -- is Environment_Task. P := Self_ID; if P.Master_Of_Task <= Independent_Task_Level then P := Environment_Task; else while P /= null and then P.Master_Of_Task >= Master loop P := P.Common.Parent; end loop; end if; Initialization.Defer_Abort_Nestable (Self_ID); begin T := New_ATCB (Num_Entries); exception when others => Initialization.Undefer_Abort_Nestable (Self_ID); raise Storage_Error with ""Cannot allocate task""; end; -- RTS_Lock is used by Abort_Dependents and Abort_Tasks. Up to this -- point, it is possible that we may be part of a family of tasks that -- is being aborted. Lock_RTS; Write_Lock (Self_ID); -- Now, we must check that we have not been aborted. If so, we should -- give up on creating this task, and simply return. if not Self_ID.Callable then pragma Assert (Self_ID.Pending_ATC_Level = Level_Completed_Task); pragma Assert (Self_ID.Pending_Action); pragma Assert (Chain.T_ID = null or else Chain.T_ID.Common.State = Unactivated); Unlock (Self_ID); Unlock_RTS; Initialization.Undefer_Abort_Nestable (Self_ID); -- ??? Should never get here pragma Assert (False); raise Standard'Abort_Signal; end if; Initialize_ATCB (Self_ID, State, Discriminants, P, Elaborated, Base_Priority, Base_CPU, Domain, Task_Info, Stack_Size, T, Success); if not Success then Free (T); Unlock (Self_ID); Unlock_RTS; Initialization.Undefer_Abort_Nestable (Self_ID); raise Storage_Error with ""Failed to initialize task""; end if; if Master = Foreign_Task_Level + 2 then -- This should not happen, except when a foreign task creates non -- library-level Ada tasks. In this case, we pretend the master is -- a regular library level task, otherwise the run-time will get -- confused when waiting for these tasks to terminate. T.Master_Of_Task := Library_Task_Level; else T.Master_Of_Task := Master; end if; T.Master_Within := T.Master_Of_Task + 1; for L in T.Entry_Calls'Range loop T.Entry_Calls (L).Self := T; T.Entry_Calls (L).Level := L; end loop; if Task_Image'Length = 0 then T.Common.Task_Image_Len := 0; else Len := 1; T.Common.Task_Image (1) := Task_Image (Task_Image'First); -- Remove unwanted blank space generated by 'Image for J in Task_Image'First + 1 .. Task_Image'Last loop if Task_Image (J) /= ' ' or else Task_Image (J - 1) /= '(' then Len := Len + 1; T.Common.Task_Image (Len) := Task_Image (J); exit when Len = T.Common.Task_Image'Last; end if; end loop; T.Common.Task_Image_Len := Len; end if; -- Note: we used to have code here to initialize T.Common.Domain, but -- that is not needed, since this is initialized in System.Tasking. Unlock (Self_ID); Unlock_RTS; -- The CPU associated to the task (if any) must belong to the -- dispatching domain. if Base_CPU /= System.Multiprocessors.Not_A_Specific_CPU and then (Base_CPU not in T.Common.Domain'Range or else not T.Common.Domain (Base_CPU)) then Initialization.Undefer_Abort_Nestable (Self_ID); raise Tasking_Error with ""CPU not in dispatching domain""; end if; -- To handle the interaction between pragma CPU and dispatching domains -- we need to signal that this task is being allocated to a processor. -- This is needed only for tasks belonging to the system domain (the -- creation of new dispatching domains can only take processors from the -- system domain) and only before the environment task calls the main -- procedure (dispatching domains cannot be created after this). if Base_CPU /= System.Multiprocessors.Not_A_Specific_CPU and then T.Common.Domain = System.Tasking.System_Domain and then not System.Tasking.Dispatching_Domains_Frozen then -- Increase the number of tasks attached to the CPU to which this -- task is being moved. Dispatching_Domain_Tasks (Base_CPU) := Dispatching_Domain_Tasks (Base_CPU) + 1; end if; -- Create the secondary stack for the task as early as possible during -- in the creation of a task, since it may be used by the operation of -- Ada code within the task. begin SSL.Create_TSD (T.Common.Compiler_Data, null, Secondary_Stack_Size); exception when others => Initialization.Undefer_Abort_Nestable (Self_ID); raise Storage_Error with ""Secondary stack could not be allocated""; end; T.Common.Activation_Link := Chain.T_ID; Chain.T_ID := T; Created_Task := T; Initialization.Undefer_Abort_Nestable (Self_ID); pragma Debug (Debug.Trace (Self_ID, ""Created task in "" & T.Master_Of_Task'Img, 'C', T)); end Create_Task; -------------------- -- Current_Master -- -------------------- function Current_Master return Master_Level is begin return STPO.Self.Master_Within; end Current_Master; ------------------ -- Enter_Master -- ------------------ procedure Enter_Master is Self_ID : constant Task_Id := STPO.Self; begin Self_ID.Master_Within := Self_ID.Master_Within + 1; pragma Debug (Debug.Trace (Self_ID, ""Enter_Master ->"" & Self_ID.Master_Within'Img, 'M')); end Enter_Master; ------------------------------- -- Expunge_Unactivated_Tasks -- ------------------------------- -- See procedure Close_Entries for the general case procedure Expunge_Unactivated_Tasks (Chain : in out Activation_Chain) is Self_ID : constant Task_Id := STPO.Self; C : Task_Id; Call : Entry_Call_Link; Temp : Task_Id; begin pragma Debug (Debug.Trace (Self_ID, ""Expunge_Unactivated_Tasks"", 'C')); Initialization.Defer_Abort_Nestable (Self_ID); -- ??? -- Experimentation has shown that abort is sometimes (but not always) -- already deferred when this is called. -- That may indicate an error. Find out what is going on C := Chain.T_ID; while C /= null loop pragma Assert (C.Common.State = Unactivated); Temp := C.Common.Activation_Link; if C.Common.State = Unactivated then Lock_RTS; Write_Lock (C); for J in 1 .. C.Entry_Num loop Queuing.Dequeue_Head (C.Entry_Queues (J), Call); pragma Assert (Call = null); end loop; Unlock (C); Initialization.Remove_From_All_Tasks_List (C); Unlock_RTS; Vulnerable_Free_Task (C); C := Temp; end if; end loop; Chain.T_ID := null; Initialization.Undefer_Abort_Nestable (Self_ID); end Expunge_Unactivated_Tasks; --------------------------- -- Finalize_Global_Tasks -- --------------------------- -- ??? -- We have a potential problem here if finalization of global objects does -- anything with signals or the timer server, since by that time those -- servers have terminated. -- It is hard to see how that would occur -- However, a better solution might be to do all this finalization -- using the global finalization chain. procedure Finalize_Global_Tasks is Self_ID : constant Task_Id := STPO.Self; Ignore_1 : Boolean; Ignore_2 : Boolean; function State (Int : System.Interrupt_Management.Interrupt_ID) return Character; pragma Import (C, State, ""__gnat_get_interrupt_state""); -- Get interrupt state for interrupt number Int. Defined in init.c Default : constant Character := 's'; -- 's' Interrupt_State pragma set state to System (use ""default"" -- system handler) begin if Self_ID.Deferral_Level = 0 then -- ??? -- In principle, we should be able to predict whether abort is -- already deferred here (and it should not be deferred yet but in -- practice it seems Finalize_Global_Tasks is being called sometimes, -- from RTS code for exceptions, with abort already deferred. Initialization.Defer_Abort_Nestable (Self_ID); -- Never undefer again end if; -- This code is only executed by the environment task pragma Assert (Self_ID = Environment_Task); -- Set Environment_Task'Callable to false to notify library-level tasks -- that it is waiting for them. Self_ID.Callable := False; -- Exit level 2 master, for normal tasks in library-level packages Complete_Master; -- Force termination of ""independent"" library-level server tasks Lock_RTS; Abort_Dependents (Self_ID); Unlock_RTS; -- We need to explicitly wait for the task to be terminated here -- because on true concurrent system, we may end this procedure before -- the tasks are really terminated. Write_Lock (Self_ID); -- If the Abort_Task signal is set to system, it means that we may -- not have been able to abort all independent tasks (in particular, -- Server_Task may be blocked, waiting for a signal), in which case, do -- not wait for Independent_Task_Count to go down to 0. We arbitrarily -- limit the number of loop iterations; if an independent task does not -- terminate, we do not want to hang here. In that case, the thread will -- be terminated when the process exits. if State (System.Interrupt_Management.Abort_Task_Interrupt) /= Default then for J in 1 .. 10 loop exit when Utilities.Independent_Task_Count = 0; -- We used to yield here, but this did not take into account low -- priority tasks that would cause dead lock in some cases (true -- FIFO scheduling). Timed_Sleep (Self_ID, 0.01, System.OS_Primitives.Relative, Self_ID.Common.State, Ignore_1, Ignore_2); end loop; end if; -- ??? On multi-processor environments, it seems that the above loop -- isn't sufficient, so we need to add an additional delay. Timed_Sleep (Self_ID, 0.01, System.OS_Primitives.Relative, Self_ID.Common.State, Ignore_1, Ignore_2); Unlock (Self_ID); -- Complete the environment task Vulnerable_Complete_Task (Self_ID); -- Handle normal task termination by the environment task, but only -- for the normal task termination. In the case of Abnormal and -- Unhandled_Exception they must have been handled before, and the -- task termination soft link must have been changed so the task -- termination routine is not executed twice. SSL.Task_Termination_Handler.all (Ada.Exceptions.Null_Occurrence); -- Finalize all library-level controlled objects if not SSL.""="" (SSL.Finalize_Library_Objects, null) then SSL.Finalize_Library_Objects.all; end if; -- Reset the soft links to non-tasking SSL.Abort_Defer := SSL.Abort_Defer_NT'Access; SSL.Abort_Undefer := SSL.Abort_Undefer_NT'Access; SSL.Lock_Task := SSL.Task_Lock_NT'Access; SSL.Unlock_Task := SSL.Task_Unlock_NT'Access; SSL.Get_Jmpbuf_Address := SSL.Get_Jmpbuf_Address_NT'Access; SSL.Set_Jmpbuf_Address := SSL.Set_Jmpbuf_Address_NT'Access; SSL.Get_Sec_Stack := SSL.Get_Sec_Stack_NT'Access; SSL.Set_Sec_Stack := SSL.Set_Sec_Stack_NT'Access; SSL.Check_Abort_Status := SSL.Check_Abort_Status_NT'Access; SSL.Get_Stack_Info := SSL.Get_Stack_Info_NT'Access; -- Don't bother trying to finalize Initialization.Global_Task_Lock -- and System.Task_Primitives.RTS_Lock. end Finalize_Global_Tasks; --------------- -- Free_Task -- --------------- procedure Free_Task (T : Task_Id) is Self_Id : constant Task_Id := Self; begin if T.Common.State = Terminated then -- It is not safe to call Abort_Defer or Write_Lock at this stage Initialization.Task_Lock (Self_Id); Lock_RTS; Initialization.Finalize_Attributes (T); Initialization.Remove_From_All_Tasks_List (T); Unlock_RTS; Initialization.Task_Unlock (Self_Id); System.Task_Primitives.Operations.Finalize_TCB (T); else -- If the task is not terminated, then mark the task as to be freed -- upon termination. T.Free_On_Termination := True; end if; end Free_Task; --------------------------- -- Move_Activation_Chain -- --------------------------- procedure Move_Activation_Chain (From, To : Activation_Chain_Access; New_Master : Master_ID) is Self_ID : constant Task_Id := STPO.Self; C : Task_Id; begin pragma Debug (Debug.Trace (Self_ID, ""Move_Activation_Chain"", 'C')); -- Nothing to do if From is empty, and we can check that without -- deferring aborts. C := From.all.T_ID; if C = null then return; end if; Initialization.Defer_Abort_Nestable (Self_ID); -- Loop through the From chain, changing their Master_Of_Task fields, -- and to find the end of the chain. loop C.Master_Of_Task := New_Master; exit when C.Common.Activation_Link = null; C := C.Common.Activation_Link; end loop; -- Hook From in at the start of To C.Common.Activation_Link := To.all.T_ID; To.all.T_ID := From.all.T_ID; -- Set From to empty From.all.T_ID := null; Initialization.Undefer_Abort_Nestable (Self_ID); end Move_Activation_Chain; ------------------ -- Task_Wrapper -- ------------------ -- The task wrapper is a procedure that is called first for each task body -- and which in turn calls the compiler-generated task body procedure. -- The wrapper's main job is to do initialization for the task. It also -- has some locally declared objects that serve as per-task local data. -- Task finalization is done by Complete_Task, which is called from an -- at-end handler that the compiler generates. procedure Task_Wrapper (Self_ID : Task_Id) is use System.Standard_Library; use System.Stack_Usage; Bottom_Of_Stack : aliased Integer; Task_Alternate_Stack : aliased SSE.Storage_Array (1 .. Alternate_Stack_Size); -- The alternate signal stack for this task, if any Use_Alternate_Stack : constant Boolean := Alternate_Stack_Size /= 0; -- Whether to use above alternate signal stack for stack overflows SEH_Table : aliased SSE.Storage_Array (1 .. 8); -- Structured Exception Registration table (2 words) procedure Install_SEH_Handler (Addr : System.Address); pragma Import (C, Install_SEH_Handler, ""__gnat_install_SEH_handler""); -- Install the SEH (Structured Exception Handling) handler Cause : Cause_Of_Termination := Normal; -- Indicates the reason why this task terminates. Normal corresponds to -- a task terminating due to completing the last statement of its body, -- or as a result of waiting on a terminate alternative. If the task -- terminates because it is being aborted then Cause will be set -- to Abnormal. If the task terminates because of an exception -- raised by the execution of its task body, then Cause is set -- to Unhandled_Exception. EO : Exception_Occurrence; -- If the task terminates because of an exception raised by the -- execution of its task body, then EO will contain the associated -- exception occurrence. Otherwise, it will contain Null_Occurrence. TH : Termination_Handler := null; -- Pointer to the protected procedure to be executed upon task -- termination. procedure Search_Fall_Back_Handler (ID : Task_Id); -- Procedure that searches recursively a fall-back handler through the -- master relationship. If the handler is found, its pointer is stored -- in TH. It stops when the handler is found or when the ID is null. ------------------------------ -- Search_Fall_Back_Handler -- ------------------------------ procedure Search_Fall_Back_Handler (ID : Task_Id) is begin -- A null Task_Id indicates that we have reached the root of the -- task hierarchy and no handler has been found. if ID = null then return; -- If there is a fall back handler, store its pointer for later -- execution. elsif ID.Common.Fall_Back_Handler /= null then TH := ID.Common.Fall_Back_Handler; -- Otherwise look for a fall back handler in the parent else Search_Fall_Back_Handler (ID.Common.Parent); end if; end Search_Fall_Back_Handler; -- Start of processing for Task_Wrapper begin pragma Assert (Self_ID.Deferral_Level = 1); Debug.Master_Hook (Self_ID, Self_ID.Common.Parent, Self_ID.Master_Of_Task); if Use_Alternate_Stack then Self_ID.Common.Task_Alternate_Stack := Task_Alternate_Stack'Address; end if; -- Set the guard page at the bottom of the stack. The call to unprotect -- the page is done in Terminate_Task Stack_Guard (Self_ID, True); -- Initialize low-level TCB components, that cannot be initialized by -- the creator. Enter_Task sets Self_ID.LL.Thread. Enter_Task (Self_ID); -- Initialize dynamic stack usage if System.Stack_Usage.Is_Enabled then declare Guard_Page_Size : constant := 16 * 1024; -- Part of the stack used as a guard page. This is an OS dependent -- value, so we need to use the maximum. This value is only used -- when the stack address is known, that is currently Windows. Small_Overflow_Guard : constant := 12 * 1024; -- Note: this used to be 4K, but was changed to 12K, since -- smaller values resulted in segmentation faults from dynamic -- stack analysis. Big_Overflow_Guard : constant := 64 * 1024 + 8 * 1024; Small_Stack_Limit : constant := 64 * 1024; -- ??? These three values are experimental, and seem to work on -- most platforms. They still need to be analyzed further. They -- also need documentation, what are they and why does the logic -- differ depending on whether the stack is large or small??? Pattern_Size : Natural := Natural (Self_ID.Common. Compiler_Data.Pri_Stack_Info.Size); -- Size of the pattern Stack_Base : Address; -- Address of the base of the stack begin Stack_Base := Self_ID.Common.Compiler_Data.Pri_Stack_Info.Base; if Stack_Base = Null_Address then -- On many platforms, we don't know the real stack base -- address. Estimate it using an address in the frame. Stack_Base := Bottom_Of_Stack'Address; -- Adjustments for inner frames Pattern_Size := Pattern_Size - (if Pattern_Size < Small_Stack_Limit then Small_Overflow_Guard else Big_Overflow_Guard); else -- Reduce by the size of the final guard page Pattern_Size := Pattern_Size - Guard_Page_Size; end if; STPO.Lock_RTS; Initialize_Analyzer (Self_ID.Common.Analyzer, Self_ID.Common.Task_Image (1 .. Self_ID.Common.Task_Image_Len), Natural (Self_ID.Common.Compiler_Data.Pri_Stack_Info.Size), SSE.To_Integer (Stack_Base), Pattern_Size); STPO.Unlock_RTS; Fill_Stack (Self_ID.Common.Analyzer); end; end if; -- We setup the SEH (Structured Exception Handling) handler if supported -- on the target. Install_SEH_Handler (SEH_Table'Address); -- Initialize exception occurrence Save_Occurrence (EO, Ada.Exceptions.Null_Occurrence); -- We lock RTS_Lock to wait for activator to finish activating the rest -- of the chain, so that everyone in the chain comes out in priority -- order. -- This also protects the value of -- Self_ID.Common.Activator.Common.Wait_Count. Lock_RTS; Unlock_RTS; if not System.Restrictions.Abort_Allowed then -- If Abort is not allowed, reset the deferral level since it will -- not get changed by the generated code. Keeping a default value -- of one would prevent some operations (e.g. select or delay) to -- proceed successfully. Self_ID.Deferral_Level := 0; end if; if Global_Task_Debug_Event_Set then Debug.Signal_Debug_Event (Debug.Debug_Event_Run, Self_ID); end if; begin -- We are separating the following portion of the code in order to -- place the exception handlers in a different block. In this way, -- we do not call Set_Jmpbuf_Address (which needs Self) before we -- set Self in Enter_Task -- Call the initialization hook if any if Global_Initialization_Handler /= null then Global_Initialization_Handler.all; end if; -- Call the task body procedure -- The task body is called with abort still deferred. That -- eliminates a dangerous window, for which we had to patch-up in -- Terminate_Task. -- During the expansion of the task body, we insert an RTS-call -- to Abort_Undefer, at the first point where abort should be -- allowed. Self_ID.Common.Task_Entry_Point (Self_ID.Common.Task_Arg); Initialization.Defer_Abort_Nestable (Self_ID); exception -- We can't call Terminate_Task in the exception handlers below, -- since there may be (e.g. in the case of GCC exception handling) -- clean ups associated with the exception handler that need to -- access task specific data. -- Defer abort so that this task can't be aborted while exiting when Standard'Abort_Signal => Initialization.Defer_Abort_Nestable (Self_ID); -- Update the cause that motivated the task termination so that -- the appropriate information is passed to the task termination -- procedure. Task termination as a result of waiting on a -- terminate alternative is a normal termination, although it is -- implemented using the abort mechanisms. if Self_ID.Terminate_Alternative then Cause := Normal; if Global_Task_Debug_Event_Set then Debug.Signal_Debug_Event (Debug.Debug_Event_Terminated, Self_ID); end if; else Cause := Abnormal; if Global_Task_Debug_Event_Set then Debug.Signal_Debug_Event (Debug.Debug_Event_Abort_Terminated, Self_ID); end if; end if; when others => -- ??? Using an E : others here causes CD2C11A to fail on Tru64 Initialization.Defer_Abort_Nestable (Self_ID); -- Perform the task specific exception tracing duty. We handle -- these outputs here and not in the common notification routine -- because we need access to tasking related data and we don't -- want to drag dependencies against tasking related units in the -- the common notification units. Additionally, no trace is ever -- triggered from the common routine for the Unhandled_Raise case -- in tasks, since an exception never appears unhandled in this -- context because of this handler. if Exception_Trace = Unhandled_Raise then Trace_Unhandled_Exception_In_Task (Self_ID); end if; -- Update the cause that motivated the task termination so that -- the appropriate information is passed to the task termination -- procedure, as well as the associated Exception_Occurrence. Cause := Unhandled_Exception; Save_Occurrence (EO, SSL.Get_Current_Excep.all.all); if Global_Task_Debug_Event_Set then Debug.Signal_Debug_Event (Debug.Debug_Event_Exception_Terminated, Self_ID); end if; end; -- Look for a task termination handler. This code is for all tasks but -- the environment task. The task termination code for the environment -- task is executed by SSL.Task_Termination_Handler. Write_Lock (Self_ID); if Self_ID.Common.Specific_Handler /= null then TH := Self_ID.Common.Specific_Handler; -- Independent tasks should not call the Fall_Back_Handler (of the -- environment task), because they are implementation artifacts that -- should be invisible to Ada programs. elsif Self_ID.Master_Of_Task /= Independent_Task_Level then -- Look for a fall-back handler following the master relationship -- for the task. As specified in ARM C.7.3 par. 9/2, ""the fall-back -- handler applies only to the dependent tasks of the task"". Hence, -- if the terminating tasks (Self_ID) had a fall-back handler, it -- would not apply to itself, so we start the search with the parent. Search_Fall_Back_Handler (Self_ID.Common.Parent); end if; Unlock (Self_ID); -- Execute the task termination handler if we found it if TH /= null then begin TH.all (Cause, Self_ID, EO); exception -- RM-C.7.3 requires all exceptions raised here to be ignored when others => null; end; end if; if System.Stack_Usage.Is_Enabled then Compute_Result (Self_ID.Common.Analyzer); Report_Result (Self_ID.Common.Analyzer); end if; Terminate_Task (Self_ID); end Task_Wrapper; -------------------- -- Terminate_Task -- -------------------- -- Before we allow the thread to exit, we must clean up. This is a delicate -- job. We must wake up the task's master, who may immediately try to -- deallocate the ATCB from the current task WHILE IT IS STILL EXECUTING. -- To avoid this, the parent task must be blocked up to the latest -- statement executed. The trouble is that we have another step that we -- also want to postpone to the very end, i.e., calling SSL.Destroy_TSD. -- We have to postpone that until the end because compiler-generated code -- is likely to try to access that data at just about any point. -- We can't call Destroy_TSD while we are holding any other locks, because -- it locks Global_Task_Lock, and our deadlock prevention rules require -- that to be the outermost lock. Our first ""solution"" was to just lock -- Global_Task_Lock in addition to the other locks, and force the parent to -- also lock this lock between its wakeup and its freeing of the ATCB. See -- Complete_Task for the parent-side of the code that has the matching -- calls to Task_Lock and Task_Unlock. That was not really a solution, -- since the operation Task_Unlock continued to access the ATCB after -- unlocking, after which the parent was observed to race ahead, deallocate -- the ATCB, and then reallocate it to another task. The call to -- Undefer_Abort in Task_Unlock by the ""terminated"" task was overwriting -- the data of the new task that reused the ATCB. To solve this problem, we -- introduced the new operation Final_Task_Unlock. procedure Terminate_Task (Self_ID : Task_Id) is Environment_Task : constant Task_Id := STPO.Environment_Task; Master_Of_Task : Integer; Deallocate : Boolean; begin Debug.Task_Termination_Hook; -- Since GCC cannot allocate stack chunks efficiently without reordering -- some of the allocations, we have to handle this unexpected situation -- here. Normally we never have to call Vulnerable_Complete_Task here. if Self_ID.Common.Activator /= null then Vulnerable_Complete_Task (Self_ID); end if; Initialization.Task_Lock (Self_ID); Master_Of_Task := Self_ID.Master_Of_Task; -- Check if the current task is an independent task If so, decrement -- the Independent_Task_Count value. if Master_Of_Task = Independent_Task_Level then Write_Lock (Environment_Task); Utilities.Independent_Task_Count := Utilities.Independent_Task_Count - 1; Unlock (Environment_Task); end if; -- Unprotect the guard page if needed Stack_Guard (Self_ID, False); Utilities.Make_Passive (Self_ID, Task_Completed => True); Deallocate := Self_ID.Free_On_Termination; pragma Assert (Check_Exit (Self_ID)); SSL.Destroy_TSD (Self_ID.Common.Compiler_Data); Initialization.Final_Task_Unlock (Self_ID); -- WARNING: past this point, this thread must assume that the ATCB has -- been deallocated, and can't access it anymore (which is why we have -- saved the Free_On_Termination flag in a temporary variable). if Deallocate then Free_Task (Self_ID); end if; if Master_Of_Task > 0 then STPO.Exit_Task; end if; end Terminate_Task; ---------------- -- Terminated -- ---------------- function Terminated (T : Task_Id) return Boolean is Self_ID : constant Task_Id := STPO.Self; Result : Boolean; begin Initialization.Defer_Abort_Nestable (Self_ID); Write_Lock (T); Result := T.Common.State = Terminated; Unlock (T); Initialization.Undefer_Abort_Nestable (Self_ID); return Result; end Terminated; ---------------------------------------- -- Trace_Unhandled_Exception_In_Task -- ---------------------------------------- procedure Trace_Unhandled_Exception_In_Task (Self_Id : Task_Id) is procedure To_Stderr (S : String); pragma Import (Ada, To_Stderr, ""__gnat_to_stderr""); use System.Soft_Links; function To_Address is new Ada.Unchecked_Conversion (Task_Id, System.Task_Primitives.Task_Address); Excep : constant Exception_Occurrence_Access := SSL.Get_Current_Excep.all; begin -- This procedure is called by the task outermost handler in -- Task_Wrapper below, so only once the task stack has been fully -- unwound. The common notification routine has been called at the -- raise point already. -- Lock to prevent unsynchronized output Initialization.Task_Lock (Self_Id); To_Stderr (""task ""); if Self_Id.Common.Task_Image_Len /= 0 then To_Stderr (Self_Id.Common.Task_Image (1 .. Self_Id.Common.Task_Image_Len)); To_Stderr (""_""); end if; To_Stderr (System.Address_Image (To_Address (Self_Id))); To_Stderr ("" terminated by unhandled exception""); To_Stderr ((1 => ASCII.LF)); To_Stderr (Exception_Information (Excep.all)); Initialization.Task_Unlock (Self_Id); end Trace_Unhandled_Exception_In_Task; ------------------------------------ -- Vulnerable_Complete_Activation -- ------------------------------------ -- As in several other places, the locks of the activator and activated -- task are both locked here. This follows our deadlock prevention lock -- ordering policy, since the activated task must be created after the -- activator. procedure Vulnerable_Complete_Activation (Self_ID : Task_Id) is Activator : constant Task_Id := Self_ID.Common.Activator; begin pragma Debug (Debug.Trace (Self_ID, ""V_Complete_Activation"", 'C')); Write_Lock (Activator); Write_Lock (Self_ID); pragma Assert (Self_ID.Common.Activator /= null); -- Remove dangling reference to Activator, since a task may outlive its -- activator. Self_ID.Common.Activator := null; -- Wake up the activator, if it is waiting for a chain of tasks to -- activate, and we are the last in the chain to complete activation. if Activator.Common.State = Activator_Sleep then Activator.Common.Wait_Count := Activator.Common.Wait_Count - 1; if Activator.Common.Wait_Count = 0 then Wakeup (Activator, Activator_Sleep); end if; end if; -- The activator raises a Tasking_Error if any task it is activating -- is completed before the activation is done. However, if the reason -- for the task completion is an abort, we do not raise an exception. -- See RM 9.2(5). if not Self_ID.Callable and then Self_ID.Pending_ATC_Level /= Level_Completed_Task then Activator.Common.Activation_Failed := True; end if; Unlock (Self_ID); Unlock (Activator); -- After the activation, active priority should be the same as base -- priority. We must unlock the Activator first, though, since it -- should not wait if we have lower priority. if Get_Priority (Self_ID) /= Self_ID.Common.Base_Priority then Write_Lock (Self_ID); Set_Priority (Self_ID, Self_ID.Common.Base_Priority); Unlock (Self_ID); end if; end Vulnerable_Complete_Activation; -------------------------------- -- Vulnerable_Complete_Master -- -------------------------------- procedure Vulnerable_Complete_Master (Self_ID : Task_Id) is C : Task_Id; P : Task_Id; CM : constant Master_Level := Self_ID.Master_Within; T : aliased Task_Id; To_Be_Freed : Task_Id; -- This is a list of ATCBs to be freed, after we have released all RTS -- locks. This is necessary because of the locking order rules, since -- the storage manager uses Global_Task_Lock. pragma Warnings (Off); function Check_Unactivated_Tasks return Boolean; pragma Warnings (On); -- Temporary error-checking code below. This is part of the checks -- added in the new run time. Call it only inside a pragma Assert. ----------------------------- -- Check_Unactivated_Tasks -- ----------------------------- function Check_Unactivated_Tasks return Boolean is begin Lock_RTS; Write_Lock (Self_ID); C := All_Tasks_List; while C /= null loop if C.Common.Activator = Self_ID and then C.Master_Of_Task = CM then return False; end if; if C.Common.Parent = Self_ID and then C.Master_Of_Task = CM then Write_Lock (C); if C.Common.State = Unactivated then return False; end if; Unlock (C); end if; C := C.Common.All_Tasks_Link; end loop; Unlock (Self_ID); Unlock_RTS; return True; end Check_Unactivated_Tasks; -- Start of processing for Vulnerable_Complete_Master begin pragma Debug (Debug.Trace (Self_ID, ""V_Complete_Master("" & CM'Img & "")"", 'C')); pragma Assert (Self_ID.Common.Wait_Count = 0); pragma Assert (Self_ID.Deferral_Level > 0 or else not System.Restrictions.Abort_Allowed); -- Count how many active dependent tasks this master currently has, and -- record this in Wait_Count. -- This count should start at zero, since it is initialized to zero for -- new tasks, and the task should not exit the sleep-loops that use this -- count until the count reaches zero. -- While we're counting, if we run across any unactivated tasks that -- belong to this master, we summarily terminate them as required by -- RM-9.2(6). Lock_RTS; Write_Lock (Self_ID); C := All_Tasks_List; while C /= null loop -- Terminate unactivated (never-to-be activated) tasks if C.Common.Activator = Self_ID and then C.Master_Of_Task = CM then -- Usually, C.Common.Activator = Self_ID implies C.Master_Of_Task -- = CM. The only case where C is pending activation by this -- task, but the master of C is not CM is in Ada 2005, when C is -- part of a return object of a build-in-place function. pragma Assert (C.Common.State = Unactivated); Write_Lock (C); C.Common.Activator := null; C.Common.State := Terminated; C.Callable := False; Utilities.Cancel_Queued_Entry_Calls (C); Unlock (C); end if; -- Count it if directly dependent on this master if C.Common.Parent = Self_ID and then C.Master_Of_Task = CM then Write_Lock (C); if C.Awake_Count /= 0 then Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1; end if; Unlock (C); end if; C := C.Common.All_Tasks_Link; end loop; Self_ID.Common.State := Master_Completion_Sleep; Unlock (Self_ID); Unlock_RTS; -- Wait until dependent tasks are all terminated or ready to terminate. -- While waiting, the task may be awakened if the task's priority needs -- changing, or this master is aborted. In the latter case, we abort the -- dependents, and resume waiting until Wait_Count goes to zero. Write_Lock (Self_ID); loop exit when Self_ID.Common.Wait_Count = 0; -- Here is a difference as compared to Complete_Master if Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level and then not Self_ID.Dependents_Aborted then Unlock (Self_ID); Lock_RTS; Abort_Dependents (Self_ID); Unlock_RTS; Write_Lock (Self_ID); else pragma Debug (Debug.Trace (Self_ID, ""master_completion_sleep"", 'C')); Sleep (Self_ID, Master_Completion_Sleep); end if; end loop; Self_ID.Common.State := Runnable; Unlock (Self_ID); -- Dependents are all terminated or on terminate alternatives. Now, -- force those on terminate alternatives to terminate, by aborting them. pragma Assert (Check_Unactivated_Tasks); if Self_ID.Alive_Count > 1 then -- ??? -- Consider finding a way to skip the following extra steps if there -- are no dependents with terminate alternatives. This could be done -- by adding another count to the ATCB, similar to Awake_Count, but -- keeping track of tasks that are on terminate alternatives. pragma Assert (Self_ID.Common.Wait_Count = 0); -- Force any remaining dependents to terminate by aborting them Lock_RTS; Abort_Dependents (Self_ID); -- Above, when we ""abort"" the dependents we are simply using this -- operation for convenience. We are not required to support the full -- abort-statement semantics; in particular, we are not required to -- immediately cancel any queued or in-service entry calls. That is -- good, because if we tried to cancel a call we would need to lock -- the caller, in order to wake the caller up. Our anti-deadlock -- rules prevent us from doing that without releasing the locks on C -- and Self_ID. Releasing and retaking those locks would be wasteful -- at best, and should not be considered further without more -- detailed analysis of potential concurrent accesses to the ATCBs -- of C and Self_ID. -- Count how many ""alive"" dependent tasks this master currently has, -- and record this in Wait_Count. This count should start at zero, -- since it is initialized to zero for new tasks, and the task should -- not exit the sleep-loops that use this count until the count -- reaches zero. pragma Assert (Self_ID.Common.Wait_Count = 0); Write_Lock (Self_ID); C := All_Tasks_List; while C /= null loop if C.Common.Parent = Self_ID and then C.Master_Of_Task = CM then Write_Lock (C); pragma Assert (C.Awake_Count = 0); if C.Alive_Count > 0 then pragma Assert (C.Terminate_Alternative); Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1; end if; Unlock (C); end if; C := C.Common.All_Tasks_Link; end loop; Self_ID.Common.State := Master_Phase_2_Sleep; Unlock (Self_ID); Unlock_RTS; -- Wait for all counted tasks to finish terminating themselves Write_Lock (Self_ID); loop exit when Self_ID.Common.Wait_Count = 0; Sleep (Self_ID, Master_Phase_2_Sleep); end loop; Self_ID.Common.State := Runnable; Unlock (Self_ID); end if; -- We don't wake up for abort here. We are already terminating just as -- fast as we can, so there is no point. -- Remove terminated tasks from the list of Self_ID's dependents, but -- don't free their ATCBs yet, because of lock order restrictions, which -- don't allow us to call ""free"" or ""malloc"" while holding any other -- locks. Instead, we put those ATCBs to be freed onto a temporary list, -- called To_Be_Freed. Lock_RTS; C := All_Tasks_List; P := null; while C /= null loop -- If Free_On_Termination is set, do nothing here, and let the -- task free itself if not already done, otherwise we risk a race -- condition where Vulnerable_Free_Task is called in the loop below, -- while the task calls Free_Task itself, in Terminate_Task. if C.Common.Parent = Self_ID and then C.Master_Of_Task >= CM and then not C.Free_On_Termination then if P /= null then P.Common.All_Tasks_Link := C.Common.All_Tasks_Link; else All_Tasks_List := C.Common.All_Tasks_Link; end if; T := C.Common.All_Tasks_Link; C.Common.All_Tasks_Link := To_Be_Freed; To_Be_Freed := C; C := T; else P := C; C := C.Common.All_Tasks_Link; end if; end loop; Unlock_RTS; -- Free all the ATCBs on the list To_Be_Freed -- The ATCBs in the list are no longer in All_Tasks_List, and after -- any interrupt entries are detached from them they should no longer -- be referenced. -- Global_Task_Lock (Task_Lock/Unlock) is locked in the loop below to -- avoid a race between a terminating task and its parent. The parent -- might try to deallocate the ACTB out from underneath the exiting -- task. Note that Free will also lock Global_Task_Lock, but that is -- OK, since this is the *one* lock for which we have a mechanism to -- support nested locking. See Task_Wrapper and its finalizer for more -- explanation. -- ??? -- The check ""T.Common.Parent /= null ..."" below is to prevent dangling -- references to terminated library-level tasks, which could otherwise -- occur during finalization of library-level objects. A better solution -- might be to hook task objects into the finalization chain and -- deallocate the ATCB when the task object is deallocated. However, -- this change is not likely to gain anything significant, since all -- this storage should be recovered en-masse when the process exits. while To_Be_Freed /= null loop T := To_Be_Freed; To_Be_Freed := T.Common.All_Tasks_Link; -- ??? On SGI there is currently no Interrupt_Manager, that's why we -- need to check if the Interrupt_Manager_ID is null. if T.Interrupt_Entry and then Interrupt_Manager_ID /= null then declare Detach_Interrupt_Entries_Index : constant Task_Entry_Index := 1; -- Corresponds to the entry index of System.Interrupts. -- Interrupt_Manager.Detach_Interrupt_Entries. Be sure -- to update this value when changing Interrupt_Manager specs. type Param_Type is access all Task_Id; Param : aliased Param_Type := T'Access; begin System.Tasking.Rendezvous.Call_Simple (Interrupt_Manager_ID, Detach_Interrupt_Entries_Index, Param'Address); end; end if; if (T.Common.Parent /= null and then T.Common.Parent.Common.Parent /= null) or else T.Master_Of_Task > Library_Task_Level then Initialization.Task_Lock (Self_ID); -- If Sec_Stack_Ptr is not null, it means that Destroy_TSD -- has not been called yet (case of an unactivated task). if T.Common.Compiler_Data.Sec_Stack_Ptr /= null then SSL.Destroy_TSD (T.Common.Compiler_Data); end if; Vulnerable_Free_Task (T); Initialization.Task_Unlock (Self_ID); end if; end loop; -- It might seem nice to let the terminated task deallocate its own -- ATCB. That would not cover the case of unactivated tasks. It also -- would force us to keep the underlying thread around past termination, -- since references to the ATCB are possible past termination. -- Currently, we get rid of the thread as soon as the task terminates, -- and let the parent recover the ATCB later. -- Some day, if we want to recover the ATCB earlier, at task -- termination, we could consider using ""fat task IDs"", that include the -- serial number with the ATCB pointer, to catch references to tasks -- that no longer have ATCBs. It is not clear how much this would gain, -- since the user-level task object would still be occupying storage. -- Make next master level up active. We don't need to lock the ATCB, -- since the value is only updated by each task for itself. Self_ID.Master_Within := CM - 1; Debug.Master_Completed_Hook (Self_ID, CM); end Vulnerable_Complete_Master; ------------------------------ -- Vulnerable_Complete_Task -- ------------------------------ -- Complete the calling task -- This procedure must be called with abort deferred. It should only be -- called by Complete_Task and Finalize_Global_Tasks (for the environment -- task). -- The effect is similar to that of Complete_Master. Differences include -- the closing of entries here, and computation of the number of active -- dependent tasks in Complete_Master. -- We don't lock Self_ID before the call to Vulnerable_Complete_Activation, -- because that does its own locking, and because we do not need the lock -- to test Self_ID.Common.Activator. That value should only be read and -- modified by Self. procedure Vulnerable_Complete_Task (Self_ID : Task_Id) is begin pragma Assert (Self_ID.Deferral_Level > 0 or else not System.Restrictions.Abort_Allowed); pragma Assert (Self_ID = Self); pragma Assert (Self_ID.Master_Within in Self_ID.Master_Of_Task .. Self_ID.Master_Of_Task + 3); pragma Assert (Self_ID.Common.Wait_Count = 0); pragma Assert (Self_ID.Open_Accepts = null); pragma Assert (Self_ID.ATC_Nesting_Level = Level_No_ATC_Occurring); pragma Debug (Debug.Trace (Self_ID, ""V_Complete_Task"", 'C')); Write_Lock (Self_ID); Self_ID.Callable := False; -- In theory, Self should have no pending entry calls left on its -- call-stack. Each async. select statement should clean its own call, -- and blocking entry calls should defer abort until the calls are -- cancelled, then clean up. Utilities.Cancel_Queued_Entry_Calls (Self_ID); Unlock (Self_ID); if Self_ID.Common.Activator /= null then Vulnerable_Complete_Activation (Self_ID); end if; -- If Self_ID.Master_Within = Self_ID.Master_Of_Task + 2 we may have -- dependent tasks for which we need to wait. Otherwise we just exit. if Self_ID.Master_Within = Self_ID.Master_Of_Task + 2 then Vulnerable_Complete_Master (Self_ID); end if; end Vulnerable_Complete_Task; -------------------------- -- Vulnerable_Free_Task -- -------------------------- -- Recover all runtime system storage associated with the task T. This -- should only be called after T has terminated and will no longer be -- referenced. -- For tasks created by an allocator that fails, due to an exception, it -- is called from Expunge_Unactivated_Tasks. -- For tasks created by elaboration of task object declarations it is -- called from the finalization code of the Task_Wrapper procedure. procedure Vulnerable_Free_Task (T : Task_Id) is begin pragma Debug (Debug.Trace (Self, ""Vulnerable_Free_Task"", 'C', T)); Write_Lock (T); Initialization.Finalize_Attributes (T); Unlock (T); System.Task_Primitives.Operations.Finalize_TCB (T); end Vulnerable_Free_Task; -- Package elaboration code begin -- Establish the Adafinal softlink -- This is not done inside the central RTS initialization routine -- to avoid with'ing this package from System.Tasking.Initialization. SSL.Adafinal := Finalize_Global_Tasks'Access; -- Establish soft links for subprograms that manipulate master_id's. -- This cannot be done when the RTS is initialized, because of various -- elaboration constraints. SSL.Current_Master := Stages.Current_Master'Access; SSL.Enter_Master := Stages.Enter_Master'Access; SSL.Complete_Master := Stages.Complete_Master'Access; end System.Tasking.Stages; ",16289,True,3383.270376481154,median "// Knight logic #include ""ThrowCommon.as"" #include ""KnightCommon.as""; #include ""RunnerCommon.as""; #include ""Hitters.as""; #include ""ShieldCommon.as""; #include ""KnockedCommon.as"" #include ""Help.as""; #include ""Requirements.as"" //attacks limited to the one time per-actor before reset. void knight_actorlimit_setup(CBlob@ this) { u16[] networkIDs; this.set(""LimitedActors"", networkIDs); } bool knight_has_hit_actor(CBlob@ this, CBlob@ actor) { u16[]@ networkIDs; this.get(""LimitedActors"", @networkIDs); return networkIDs.find(actor.getNetworkID()) >= 0; } u32 knight_hit_actor_count(CBlob@ this) { u16[]@ networkIDs; this.get(""LimitedActors"", @networkIDs); return networkIDs.length; } void knight_add_actor_limit(CBlob@ this, CBlob@ actor) { this.push(""LimitedActors"", actor.getNetworkID()); } void knight_clear_actor_limits(CBlob@ this) { this.clear(""LimitedActors""); } void onInit(CBlob@ this) { KnightInfo knight; knight.state = KnightStates::normal; knight.swordTimer = 0; knight.slideTime = 0; knight.doubleslash = false; knight.shield_down = getGameTime(); knight.tileDestructionLimiter = 0; this.set(""knightInfo"", @knight); KnightState@[] states; states.push_back(NormalState()); states.push_back(ShieldingState()); states.push_back(ShieldGlideState()); states.push_back(ShieldSlideState()); states.push_back(SwordDrawnState()); states.push_back(CutState(KnightStates::sword_cut_up)); states.push_back(CutState(KnightStates::sword_cut_mid)); states.push_back(CutState(KnightStates::sword_cut_mid_down)); states.push_back(CutState(KnightStates::sword_cut_mid)); states.push_back(CutState(KnightStates::sword_cut_down)); states.push_back(SlashState(KnightStates::sword_power)); states.push_back(SlashState(KnightStates::sword_power_super)); states.push_back(ResheathState(KnightStates::resheathing_cut, KnightVars::resheath_cut_time)); states.push_back(ResheathState(KnightStates::resheathing_slash, KnightVars::resheath_slash_time)); this.set(""knightStates"", @states); this.set_s32(""currentKnightState"", 0); this.set_f32(""gib health"", -1.5f); addShieldVars(this, SHIELD_BLOCK_ANGLE, 2.0f, 5.0f); knight_actorlimit_setup(this); this.getShape().SetRotationsAllowed(false); this.getShape().getConsts().net_threshold_multiplier = 0.5f; this.Tag(""player""); this.Tag(""flesh""); this.addCommandID(""get bomb""); this.push(""names to activate"", ""keg""); this.set_u8(""bomb type"", 255); for (uint i = 0; i < bombTypeNames.length; i++) { this.addCommandID(""pick "" + bombTypeNames[i]); } //centered on bomb select //this.set_Vec2f(""inventory offset"", Vec2f(0.0f, 122.0f)); //centered on inventory this.set_Vec2f(""inventory offset"", Vec2f(0.0f, 0.0f)); SetHelp(this, ""help self action"", ""knight"", getTranslatedString(""$Jab$Jab $LMB$""), """", 4); SetHelp(this, ""help self action2"", ""knight"", getTranslatedString(""$Shield$Shield $KEY_HOLD$$RMB$""), """", 4); this.getCurrentScript().runFlags |= Script::tick_not_attached; this.getCurrentScript().removeIfTag = ""dead""; } void onSetPlayer(CBlob@ this, CPlayer@ player) { if (player !is null) { player.SetScoreboardVars(""ScoreboardIcons.png"", 3, Vec2f(16, 16)); } } void RunStateMachine(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { KnightState@[]@ states; if (!this.get(""knightStates"", @states)) { return; } s32 currentStateIndex = this.get_s32(""currentKnightState""); if (getNet().isClient()) { if (this.exists(""serverKnightState"")) { s32 serverStateIndex = this.get_s32(""serverKnightState""); this.set_s32(""serverKnightState"", -1); if (serverStateIndex != -1 && serverStateIndex != currentStateIndex) { KnightState@ serverState = states[serverStateIndex]; u8 net_state = states[serverStateIndex].getStateValue(); if (this.isMyPlayer()) { if (net_state >= KnightStates::sword_cut_mid && net_state <= KnightStates::sword_power_super) { if (knight.state != KnightStates::sword_drawn && knight.state != KnightStates::resheathing_cut && knight.state != KnightStates::resheathing_slash) { if ((getGameTime() - serverState.stateEnteredTime) > 20) { knight.state = net_state; serverState.stateEnteredTime = getGameTime(); serverState.StateEntered(this, knight, serverState.getStateValue()); this.set_s32(""currentKnightState"", serverStateIndex); currentStateIndex = serverStateIndex; } } } } else { knight.state = net_state; serverState.stateEnteredTime = getGameTime(); serverState.StateEntered(this, knight, serverState.getStateValue()); this.set_s32(""currentKnightState"", serverStateIndex); currentStateIndex = serverStateIndex; } } } } u8 state = knight.state; KnightState@ currentState = states[currentStateIndex]; bool tickNext = false; tickNext = currentState.TickState(this, knight, moveVars); if (state != knight.state) { for (s32 i = 0; i < states.size(); i++) { if (states[i].getStateValue() == knight.state) { s32 nextStateIndex = i; KnightState@ nextState = states[nextStateIndex]; currentState.StateExited(this, knight, nextState.getStateValue()); nextState.stateEnteredTime = getGameTime(); nextState.StateEntered(this, knight, currentState.getStateValue()); this.set_s32(""currentKnightState"", nextStateIndex); if (getNet().isServer() && knight.state >= KnightStates::sword_drawn && knight.state <= KnightStates::sword_power_super) { this.set_s32(""serverKnightState"", nextStateIndex); this.Sync(""serverKnightState"", true); } if (tickNext) { RunStateMachine(this, knight, moveVars); } break; } } } } void onTick(CBlob@ this) { bool knocked = isKnocked(this); CHUD@ hud = getHUD(); //knight logic stuff //get the vars to turn various other scripts on/off RunnerMoveVars@ moveVars; if (!this.get(""moveVars"", @moveVars)) { return; } KnightInfo@ knight; if (!this.get(""knightInfo"", @knight)) { return; } if (this.isInInventory()) { //prevent players from insta-slashing when exiting crates knight.state = 0; knight.swordTimer = 0; knight.slideTime = 0; knight.doubleslash = false; hud.SetCursorFrame(0); this.set_s32(""currentKnightState"", 0); return; } Vec2f pos = this.getPosition(); Vec2f vel = this.getVelocity(); Vec2f aimpos = this.getAimPos(); const bool inair = (!this.isOnGround() && !this.isOnLadder()); Vec2f vec; const int direction = this.getAimDirection(vec); const f32 side = (this.isFacingLeft() ? 1.0f : -1.0f); bool shieldState = isShieldState(knight.state); bool specialShieldState = isSpecialShieldState(knight.state); bool swordState = isSwordState(knight.state); bool pressed_a1 = this.isKeyPressed(key_action1); bool pressed_a2 = this.isKeyPressed(key_action2); bool walking = (this.isKeyPressed(key_left) || this.isKeyPressed(key_right)); const bool myplayer = this.isMyPlayer(); if (getNet().isClient() && !this.isInInventory() && myplayer) //Knight charge cursor { SwordCursorUpdate(this, knight); } if (knocked) { knight.state = KnightStates::normal; //cancel any attacks or shielding knight.swordTimer = 0; knight.slideTime = 0; knight.doubleslash = false; this.set_s32(""currentKnightState"", 0); pressed_a1 = false; pressed_a2 = false; walking = false; } else { RunStateMachine(this, knight, moveVars); } //throwing bombs if (myplayer) { // space if (this.isKeyJustPressed(key_action3)) { CBlob@ carried = this.getCarriedBlob(); bool holding = carried !is null;// && carried.hasTag(""exploding""); CInventory@ inv = this.getInventory(); bool thrown = false; u8 bombType = this.get_u8(""bomb type""); if (bombType == 255) { SetFirstAvailableBomb(this); bombType = this.get_u8(""bomb type""); } if (bombType < bombTypeNames.length) { for (int i = 0; i < inv.getItemsCount(); i++) { CBlob@ item = inv.getItem(i); const string itemname = item.getName(); if (!holding && bombTypeNames[bombType] == itemname) { if (bombType >= 2) { this.server_Pickup(item); client_SendThrowOrActivateCommand(this); thrown = true; } else { CBitStream params; params.write_u8(bombType); this.SendCommand(this.getCommandID(""get bomb""), params); thrown = true; } break; } } } if (!thrown) { client_SendThrowOrActivateCommand(this); SetFirstAvailableBomb(this); } } // help if (this.isKeyJustPressed(key_action1) && getGameTime() > 150) { SetHelp(this, ""help self action"", ""knight"", getTranslatedString(""$Slash$ Slash! $KEY_HOLD$$LMB$""), """", 13); } } //setting the shield direction properly if (shieldState) { int horiz = this.isFacingLeft() ? -1 : 1; setShieldEnabled(this, true); setShieldAngle(this, SHIELD_BLOCK_ANGLE); if (specialShieldState) { if (knight.state == KnightStates::shieldgliding) { setShieldDirection(this, Vec2f(0, -1)); setShieldAngle(this, SHIELD_BLOCK_ANGLE_GLIDING); } else //shield dropping { setShieldDirection(this, Vec2f(horiz, 2)); setShieldAngle(this, SHIELD_BLOCK_ANGLE_SLIDING); } this.Tag(""prevent crouch""); } else if (walking) { if (direction == 0) //forward { setShieldDirection(this, Vec2f(horiz, 0)); } else if (direction == 1) //down { setShieldDirection(this, Vec2f(horiz, 3)); } else { setShieldDirection(this, Vec2f(horiz, -3)); } this.Tag(""prevent crouch""); } else { if (direction == 0) //forward { setShieldDirection(this, Vec2f(horiz, 0)); } else if (direction == 1) //down { setShieldDirection(this, Vec2f(horiz, 3)); } else //up { if (vec.y < -0.97) { setShieldDirection(this, Vec2f(0, -1)); } else { setShieldDirection(this, Vec2f(horiz, -3)); } } } // shield up = collideable if ((knight.state == KnightStates::shielding && direction == -1) || knight.state == KnightStates::shieldgliding) { if (!this.hasTag(""shieldplatform"")) { this.getShape().checkCollisionsAgain = true; this.Tag(""shieldplatform""); } } else { if (this.hasTag(""shieldplatform"")) { this.getShape().checkCollisionsAgain = true; this.Untag(""shieldplatform""); } } } else { setShieldEnabled(this, false); if (this.hasTag(""shieldplatform"")) { this.getShape().checkCollisionsAgain = true; this.Untag(""shieldplatform""); } } if (!swordState && getNet().isServer()) { knight_clear_actor_limits(this); } } bool getInAir(CBlob@ this) { bool inair = (!this.isOnGround() && !this.isOnLadder()); return inair; } void ShieldMovement(RunnerMoveVars@ moveVars) { moveVars.jumpFactor *= 0.5f; moveVars.walkFactor *= 0.9f; } class NormalState : KnightState { u8 getStateValue() { return KnightStates::normal; } void StateEntered(CBlob@ this, KnightInfo@ knight, u8 previous_state) { knight.swordTimer = 0; this.set_u8(""swordSheathPlayed"", 0); this.set_u8(""animeSwordPlayed"", 0); } bool TickState(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { if (this.isKeyPressed(key_action1) && !moveVars.wallsliding) { knight.state = KnightStates::sword_drawn; return true; } else if (this.isKeyPressed(key_action2)) { if (canRaiseShield(this)) { knight.state = KnightStates::shielding; return true; } else { resetShieldKnockdown(this); } ShieldMovement(moveVars); } return false; } } bool getForceDrop(CBlob@ this, RunnerMoveVars@ moveVars) { Vec2f vel = this.getVelocity(); bool forcedrop = (vel.y > Maths::Max(Maths::Abs(vel.x), 2.0f) && moveVars.fallCount > KnightVars::glide_down_time); return forcedrop; } class ShieldingState : KnightState { u8 getStateValue() { return KnightStates::shielding; } void StateEntered(CBlob@ this, KnightInfo@ knight, u8 previous_state) { knight.swordTimer = 0; } bool TickState(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { if (this.isKeyPressed(key_action1)) { knight.state = KnightStates::sword_drawn; return true; } else if (!this.isKeyPressed(key_action2)) { knight.state = KnightStates::normal; return false; } Vec2f pos = this.getPosition(); bool forcedrop = getForceDrop(this, moveVars); bool inair = getInAir(this); if (inair && !this.isInWater()) { Vec2f vec; const int direction = this.getAimDirection(vec); if (direction == -1 && !forcedrop && !getMap().isInWater(pos + Vec2f(0, 16)) && !moveVars.wallsliding) { knight.state = KnightStates::shieldgliding; return true; } else if (forcedrop || direction == 1) { knight.state = KnightStates::shielddropping; return true; } } ShieldMovement(moveVars); return false; } } class ShieldGlideState : KnightState { u8 getStateValue() { return KnightStates::shieldgliding; } void StateEntered(CBlob@ this, KnightInfo@ knight, u8 previous_state) { knight.swordTimer = 0; } bool TickState(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { if (this.isKeyPressed(key_action1)) { knight.state = KnightStates::sword_drawn; return true; } else if (!this.isKeyPressed(key_action2)) { knight.state = KnightStates::normal; return false; } Vec2f pos = this.getPosition(); bool forcedrop = getForceDrop(this, moveVars); bool inair = getInAir(this); if (inair && !this.isInWater()) { Vec2f vec; const int direction = this.getAimDirection(vec); if (direction == -1 && !forcedrop && !getMap().isInWater(pos + Vec2f(0, 16)) && !moveVars.wallsliding) { // already in KnightStates::shieldgliding; } else if (forcedrop || direction == 1) { knight.state = KnightStates::shielddropping; return true; } else { knight.state = KnightStates::shielding; ShieldMovement(moveVars); return false; } } ShieldMovement(moveVars); if (this.isInWater() || forcedrop) { knight.state = KnightStates::shielding; } else { Vec2f vel = this.getVelocity(); moveVars.stoppingFactor *= 0.5f; f32 glide_amount = 1.0f - (moveVars.fallCount / f32(KnightVars::glide_down_time * 2)); if (vel.y > -1.0f) { this.AddForce(Vec2f(0, -20.0f * glide_amount)); } if (!inair) { knight.state = KnightStates::shielding; } } return false; } } class ShieldSlideState : KnightState { u8 getStateValue() { return KnightStates::shielddropping; } void StateEntered(CBlob@ this, KnightInfo@ knight, u8 previous_state) { knight.swordTimer = 0; } bool TickState(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { if (this.isKeyPressed(key_action1)) { knight.state = KnightStates::sword_drawn; return true; } else if (!this.isKeyPressed(key_action2)) { knight.state = KnightStates::normal; return false; } Vec2f pos = this.getPosition(); bool forcedrop = getForceDrop(this, moveVars); bool inair = getInAir(this); if (inair && !this.isInWater()) { Vec2f vec; const int direction = this.getAimDirection(vec); if (direction == -1 && !forcedrop && !getMap().isInWater(pos + Vec2f(0, 16)) && !moveVars.wallsliding) { knight.state = KnightStates::shieldgliding; return true; } else if (forcedrop || direction == 1) { // already in KnightStates::shielddropping; knight.slideTime = 0; } else { knight.state = KnightStates::shielding; ShieldMovement(moveVars); return false; } } ShieldMovement(moveVars); Vec2f vel = this.getVelocity(); if (this.isInWater()) { if (vel.y > 1.5f && Maths::Abs(vel.x) * 3 > Maths::Abs(vel.y)) { vel.y = Maths::Max(-Maths::Abs(vel.y) + 1.0f, -8.0); this.setVelocity(vel); } else { knight.state = KnightStates::shielding; } } if (!inair && this.getShape().vellen < 1.0f) { knight.state = KnightStates::shielding; } else { // faster sliding if (!inair) { knight.slideTime++; if (knight.slideTime > 0) { if (knight.slideTime == 5) { this.getSprite().PlayRandomSound(""/Scrape""); } f32 factor = Maths::Max(1.0f, 2.2f / Maths::Sqrt(knight.slideTime)); moveVars.walkFactor *= factor; if (knight.slideTime > 30) { moveVars.walkFactor *= 0.75f; if (knight.slideTime > 45) { knight.state = KnightStates::shielding; } } else if (XORRandom(3) == 0) { Vec2f pos = this.getPosition(); Vec2f velr = getRandomVelocity(!this.isFacingLeft() ? 70 : 110, 4.3f, 40.0f); velr.y = -Maths::Abs(velr.y) + Maths::Abs(velr.x) / 3.0f - 2.0f - float(XORRandom(100)) / 100.0f; ParticlePixel(pos, velr, SColor(255, 255, 255, 0), true); } } } else if (vel.y > 1.05f) { knight.slideTime = 0; } } return false; } } s32 getSwordTimerDelta(KnightInfo@ knight) { s32 delta = knight.swordTimer; if (knight.swordTimer < 128) { knight.swordTimer++; } return delta; } void AttackMovement(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { Vec2f vel = this.getVelocity(); bool strong = (knight.swordTimer > KnightVars::slash_charge_level2); moveVars.jumpFactor *= (strong ? 0.6f : 0.8f); moveVars.walkFactor *= (strong ? 0.8f : 0.9f); bool inair = getInAir(this); if (!inair) { this.AddForce(Vec2f(vel.x * -5.0, 0.0f)); //horizontal slowing force (prevents SANICS) } moveVars.canVault = false; } class SwordDrawnState : KnightState { u8 getStateValue() { return KnightStates::sword_drawn; } void StateEntered(CBlob@ this, KnightInfo@ knight, u8 previous_state) { knight.swordTimer = 0; this.set_u8(""swordSheathPlayed"", 0); this.set_u8(""animeSwordPlayed"", 0); } bool TickState(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { if (moveVars.wallsliding) { knight.state = KnightStates::normal; return false; } Vec2f pos = this.getPosition(); if (getNet().isClient()) { const bool myplayer = this.isMyPlayer(); if (knight.swordTimer == KnightVars::slash_charge_level2) { Sound::Play(""AnimeSword.ogg"", pos, myplayer ? 1.3f : 0.7f); this.set_u8(""animeSwordPlayed"", 1); } else if (knight.swordTimer == KnightVars::slash_charge) { Sound::Play(""SwordSheath.ogg"", pos, myplayer ? 1.3f : 0.7f); this.set_u8(""swordSheathPlayed"", 1); } } if (knight.swordTimer >= KnightVars::slash_charge_limit) { Sound::Play(""/Stun"", pos, 1.0f, this.getSexNum() == 0 ? 1.0f : 1.5f); setKnocked(this, 15); knight.state = KnightStates::normal; } AttackMovement(this, knight, moveVars); s32 delta = getSwordTimerDelta(knight); if (!this.isKeyPressed(key_action1)) { if (delta < KnightVars::slash_charge) { Vec2f vec; const int direction = this.getAimDirection(vec); if (direction == -1) { knight.state = KnightStates::sword_cut_up; } else if (direction == 0) { Vec2f aimpos = this.getAimPos(); Vec2f pos = this.getPosition(); if (aimpos.y < pos.y) { knight.state = KnightStates::sword_cut_mid; } else { knight.state = KnightStates::sword_cut_mid_down; } } else { knight.state = KnightStates::sword_cut_down; } } else if (delta < KnightVars::slash_charge_level2) { knight.state = KnightStates::sword_power; } else if(delta < KnightVars::slash_charge_limit) { knight.state = KnightStates::sword_power_super; } } return false; } } class CutState : KnightState { u8 state; CutState(u8 s) { state = s; } u8 getStateValue() { return state; } void StateEntered(CBlob@ this, KnightInfo@ knight, u8 previous_state) { knight_clear_actor_limits(this); knight.swordTimer = 0; } bool TickState(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { if (moveVars.wallsliding) { knight.state = KnightStates::normal; return false; } this.Tag(""prevent crouch""); AttackMovement(this, knight, moveVars); s32 delta = getSwordTimerDelta(knight); if (delta == DELTA_BEGIN_ATTACK) { Sound::Play(""/SwordSlash"", this.getPosition()); } else if (delta > DELTA_BEGIN_ATTACK && delta < DELTA_END_ATTACK) { f32 attackarc = 90.0f; f32 attackAngle = getCutAngle(this, knight.state); if (knight.state == KnightStates::sword_cut_down) { attackarc *= 0.9f; } DoAttack(this, 1.0f, attackAngle, attackarc, Hitters::sword, delta, knight); } else if (delta >= 9) { knight.state = KnightStates::resheathing_cut; } return false; } } Vec2f getSlashDirection(CBlob@ this) { Vec2f vel = this.getVelocity(); Vec2f aiming_direction = vel; aiming_direction.y *= 2; aiming_direction.Normalize(); return aiming_direction; } class SlashState : KnightState { u8 state; SlashState(u8 s) { state = s; } u8 getStateValue() { return state; } void StateEntered(CBlob@ this, KnightInfo@ knight, u8 previous_state) { knight_clear_actor_limits(this); knight.swordTimer = 0; knight.slash_direction = getSlashDirection(this); } bool TickState(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { if (moveVars.wallsliding) { knight.state = KnightStates::normal; return false; } if (getNet().isClient()) { const bool myplayer = this.isMyPlayer(); Vec2f pos = this.getPosition(); if (knight.state == KnightStates::sword_power_super && this.get_u8(""animeSwordPlayed"") == 0) { Sound::Play(""AnimeSword.ogg"", pos, myplayer ? 1.3f : 0.7f); this.set_u8(""animeSwordPlayed"", 1); this.set_u8(""swordSheathPlayed"", 1); } else if (knight.state == KnightStates::sword_power && this.get_u8(""swordSheathPlayed"") == 0) { Sound::Play(""SwordSheath.ogg"", pos, myplayer ? 1.3f : 0.7f); this.set_u8(""swordSheathPlayed"", 1); } } this.Tag(""prevent crouch""); AttackMovement(this, knight, moveVars); s32 delta = getSwordTimerDelta(knight); if (knight.state == KnightStates::sword_power_super && this.isKeyJustPressed(key_action1)) { knight.doubleslash = true; } if (delta == 2) { Sound::Play(""/ArgLong"", this.getPosition()); Sound::Play(""/SwordSlash"", this.getPosition()); } else if (delta > DELTA_BEGIN_ATTACK && delta < 10) { Vec2f vec; this.getAimDirection(vec); DoAttack(this, 2.0f, -(vec.Angle()), 120.0f, Hitters::sword, delta, knight); } else if (delta >= KnightVars::slash_time || (knight.doubleslash && delta >= KnightVars::double_slash_time)) { if (knight.doubleslash) { knight.doubleslash = false; knight.state = KnightStates::sword_power; } else { knight.state = KnightStates::resheathing_slash; } } Vec2f vel = this.getVelocity(); if ((knight.state == KnightStates::sword_power || knight.state == KnightStates::sword_power_super) && delta < KnightVars::slash_move_time) { if (Maths::Abs(vel.x) < KnightVars::slash_move_max_speed && vel.y > -KnightVars::slash_move_max_speed) { Vec2f slash_vel = knight.slash_direction * this.getMass() * 0.5f; this.AddForce(slash_vel); } } return false; } } class ResheathState : KnightState { u8 state; s32 time; ResheathState(u8 s, s32 t) { state = s; time = t; } u8 getStateValue() { return state; } void StateEntered(CBlob@ this, KnightInfo@ knight, u8 previous_state) { knight.swordTimer = 0; this.set_u8(""swordSheathPlayed"", 0); this.set_u8(""animeSwordPlayed"", 0); } bool TickState(CBlob@ this, KnightInfo@ knight, RunnerMoveVars@ moveVars) { if (moveVars.wallsliding) { knight.state = KnightStates::normal; return false; } else if (this.isKeyPressed(key_action1)) { knight.state = KnightStates::sword_drawn; return true; } AttackMovement(this, knight, moveVars); s32 delta = getSwordTimerDelta(knight); if (delta > time) { knight.state = KnightStates::normal; } return false; } } void SwordCursorUpdate(CBlob@ this, KnightInfo@ knight) { if (knight.swordTimer >= KnightVars::slash_charge_level2 || knight.doubleslash || knight.state == KnightStates::sword_power_super) { getHUD().SetCursorFrame(19); } else if (knight.swordTimer >= KnightVars::slash_charge) { int frame = 1 + int((float(knight.swordTimer - KnightVars::slash_charge) / (KnightVars::slash_charge_level2 - KnightVars::slash_charge)) * 9) * 2; getHUD().SetCursorFrame(frame); } // the yellow circle stays for the duration of a slash, helpful for newplayers (note: you cant attack while its yellow) else if (knight.state == KnightStates::normal || knight.state == KnightStates::resheathing_cut || knight.state == KnightStates::resheathing_slash) // disappear after slash is done // the yellow circle dissapears after mouse button release, more intuitive for improving slash timing // else if (knight.swordTimer == 0) (disappear right after mouse release) { getHUD().SetCursorFrame(0); } else if (knight.swordTimer < KnightVars::slash_charge && knight.state == KnightStates::sword_drawn) { int frame = 2 + int((float(knight.swordTimer) / KnightVars::slash_charge) * 8) * 2; if (knight.swordTimer <= KnightVars::resheath_cut_time) //prevent from appearing when jabbing/jab spamming { getHUD().SetCursorFrame(0); } else { getHUD().SetCursorFrame(frame); } } } void onCommand(CBlob@ this, u8 cmd, CBitStream @params) { if (cmd == this.getCommandID(""get bomb"")) { const u8 bombType = params.read_u8(); if (bombType >= bombTypeNames.length) return; const string bombTypeName = bombTypeNames[bombType]; this.Tag(bombTypeName + "" done activate""); if (hasItem(this, bombTypeName)) { if (bombType == 0) { if (getNet().isServer()) { CBlob @blob = server_CreateBlob(""bomb"", this.getTeamNum(), this.getPosition()); if (blob !is null) { TakeItem(this, bombTypeName); this.server_Pickup(blob); } } } else if (bombType == 1) { if (getNet().isServer()) { CBlob @blob = server_CreateBlob(""waterbomb"", this.getTeamNum(), this.getPosition()); if (blob !is null) { TakeItem(this, bombTypeName); this.server_Pickup(blob); blob.set_f32(""map_damage_ratio"", 0.0f); blob.set_f32(""explosive_damage"", 0.0f); blob.set_f32(""explosive_radius"", 92.0f); blob.set_bool(""map_damage_raycast"", false); blob.set_string(""custom_explosion_sound"", ""/GlassBreak""); blob.set_u8(""custom_hitter"", Hitters::water); blob.Tag(""splash ray cast""); } } } else { } SetFirstAvailableBomb(this); } } else if (cmd == this.getCommandID(""cycle"")) //from standardcontrols { // cycle bombs u8 type = this.get_u8(""bomb type""); int count = 0; while (count < bombTypeNames.length) { type++; count++; if (type >= bombTypeNames.length) type = 0; if (this.getBlobCount(bombTypeNames[type]) > 0) { this.set_u8(""bomb type"", type); if (this.isMyPlayer()) { Sound::Play(""/CycleInventory.ogg""); } break; } } } else if (cmd == this.getCommandID(""activate/throw"")) { SetFirstAvailableBomb(this); } else { for (uint i = 0; i < bombTypeNames.length; i++) { if (cmd == this.getCommandID(""pick "" + bombTypeNames[i])) { this.set_u8(""bomb type"", i); break; } } } } ///////////////////////////////////////////////// bool isJab(f32 damage) { return damage < 1.5f; } void DoAttack(CBlob@ this, f32 damage, f32 aimangle, f32 arcdegrees, u8 type, int deltaInt, KnightInfo@ info) { if (!getNet().isServer()) { return; } if (aimangle < 0.0f) { aimangle += 360.0f; } Vec2f blobPos = this.getPosition(); Vec2f vel = this.getVelocity(); Vec2f thinghy(1, 0); thinghy.RotateBy(aimangle); Vec2f pos = blobPos - thinghy * 6.0f + vel + Vec2f(0, -2); vel.Normalize(); f32 attack_distance = Maths::Min(DEFAULT_ATTACK_DISTANCE + Maths::Max(0.0f, 1.75f * this.getShape().vellen * (vel * thinghy)), MAX_ATTACK_DISTANCE); f32 radius = this.getRadius(); CMap@ map = this.getMap(); bool dontHitMore = false; bool dontHitMoreMap = false; const bool jab = isJab(damage); bool dontHitMoreLogs = false; //get the actual aim angle f32 exact_aimangle = (this.getAimPos() - blobPos).Angle(); // this gathers HitInfo objects which contain blob or tile hit information HitInfo@[] hitInfos; if (map.getHitInfosFromArc(pos, aimangle, arcdegrees, radius + attack_distance, this, @hitInfos)) { //HitInfo objects are sorted, first come closest hits for (uint i = 0; i < hitInfos.length; i++) { HitInfo@ hi = hitInfos[i]; CBlob@ b = hi.blob; if (b !is null && !dontHitMore) // blob { if (b.hasTag(""ignore sword"")) continue; //big things block attacks const bool large = b.hasTag(""blocks sword"") && !b.isAttached() && b.isCollidable(); if (!canHit(this, b)) { // no TK if (large) dontHitMore = true; continue; } if (knight_has_hit_actor(this, b)) { if (large) dontHitMore = true; continue; } f32 temp_damage = damage; knight_add_actor_limit(this, b); if (!dontHitMore && (b.getName() != ""log"" || !dontHitMoreLogs)) { Vec2f velocity = b.getPosition() - pos; if (b.getName() == ""log"") { temp_damage /= 3; dontHitMoreLogs = true; CBlob@ wood = server_CreateBlobNoInit(""mat_wood""); if (wood !is null) { int quantity = Maths::Ceil(float(temp_damage) * 20.0f); int max_quantity = b.getHealth() / 0.024f; // initial log health / max mats quantity = Maths::Max( Maths::Min(quantity, max_quantity), 0 ); wood.Tag('custom quantity'); wood.Init(); wood.setPosition(hi.hitpos); wood.server_SetQuantity(quantity); } } this.server_Hit(b, hi.hitpos, velocity, temp_damage, type, true); // server_Hit() is server-side only // end hitting if we hit something solid, don't if its flesh if (large) { dontHitMore = true; } } } else // hitmap if (!dontHitMoreMap && (deltaInt == DELTA_BEGIN_ATTACK + 1)) { bool ground = map.isTileGround(hi.tile); bool dirt_stone = map.isTileStone(hi.tile); bool gold = map.isTileGold(hi.tile); bool wood = map.isTileWood(hi.tile); if (ground || wood || dirt_stone || gold) { Vec2f tpos = map.getTileWorldPosition(hi.tileOffset) + Vec2f(4, 4); Vec2f offset = (tpos - blobPos); f32 tileangle = offset.Angle(); f32 dif = Maths::Abs(exact_aimangle - tileangle); if (dif > 180) dif -= 360; if (dif < -180) dif += 360; dif = Maths::Abs(dif); //print(""dif: ""+dif); if (dif < 20.0f) { //detect corner int check_x = -(offset.x > 0 ? -1 : 1); int check_y = -(offset.y > 0 ? -1 : 1); if (map.isTileSolid(hi.hitpos - Vec2f(map.tilesize * check_x, 0)) && map.isTileSolid(hi.hitpos - Vec2f(0, map.tilesize * check_y))) continue; bool canhit = true; //default true if not jab if (jab) //fake damage { info.tileDestructionLimiter++; canhit = ((info.tileDestructionLimiter % ((wood || dirt_stone) ? 3 : 2)) == 0); } else //reset fake dmg for next time { info.tileDestructionLimiter = 0; } //dont dig through no build zones canhit = canhit && map.getSectorAtPosition(tpos, ""no build"") is null; dontHitMoreMap = true; if (canhit) { map.server_DestroyTile(hi.hitpos, 0.1f, this); if (gold) { // Note: 0.1f damage doesn't harvest anything I guess // This puts it in inventory - include MaterialCommon //Material::fromTile(this, hi.tile, 1.f); CBlob@ ore = server_CreateBlobNoInit(""mat_gold""); if (ore !is null) { ore.Tag('custom quantity'); ore.Init(); ore.setPosition(hi.hitpos); ore.server_SetQuantity(4); } } } } } } } } // destroy grass if (((aimangle >= 0.0f && aimangle <= 180.0f) || damage > 1.0f) && // aiming down or slash (deltaInt == DELTA_BEGIN_ATTACK + 1)) // hit only once { f32 tilesize = map.tilesize; int steps = Maths::Ceil(2 * radius / tilesize); int sign = this.isFacingLeft() ? -1 : 1; for (int y = 0; y < steps; y++) for (int x = 0; x < steps; x++) { Vec2f tilepos = blobPos + Vec2f(x * tilesize * sign, y * tilesize); TileType tile = map.getTile(tilepos).type; if (map.isTileGrass(tile)) { map.server_DestroyTile(tilepos, damage, this); if (damage <= 1.0f) { return; } } } } } bool isSliding(KnightInfo@ knight) { return (knight.slideTime > 0 && knight.slideTime < 45); } // shieldbash void onCollision(CBlob@ this, CBlob@ blob, bool solid, Vec2f normal, Vec2f point1) { //return if we didn't collide or if it's teamie if (blob is null || !solid || this.getTeamNum() == blob.getTeamNum()) { return; } const bool onground = this.isOnGround(); if (this.getShape().vellen > SHIELD_KNOCK_VELOCITY || onground) { KnightInfo@ knight; if (!this.get(""knightInfo"", @knight)) { return; } //printf(""knight.stat "" + knight.state ); if (knight.state == KnightStates::shielddropping && (!onground || isSliding(knight)) && (blob.getShape() !is null && !blob.getShape().isStatic()) && !isKnocked(blob)) { Vec2f pos = this.getPosition(); Vec2f vel = this.getOldVelocity(); vel.Normalize(); //printf(""nor "" + vel * normal ); if (vel * normal < 0.0f && knight_hit_actor_count(this) == 0) //only bash one thing per tick { ShieldVars@ shieldVars = getShieldVars(this); //printf(""shi "" + shieldVars.direction * normal ); if (shieldVars.direction * normal < 0.0f) { knight_add_actor_limit(this, blob); this.server_Hit(blob, pos, vel, 0.0f, Hitters::shield); Vec2f force = Vec2f(shieldVars.direction.x * this.getMass(), -this.getMass()) * 3.0f; blob.AddForce(force); this.AddForce(Vec2f(-force.x, force.y)); } } } } } //a little push forward void pushForward(CBlob@ this, f32 normalForce, f32 pushingForce, f32 verticalForce) { f32 facing_sign = this.isFacingLeft() ? -1.0f : 1.0f ; bool pushing_in_facing_direction = (facing_sign < 0.0f && this.isKeyPressed(key_left)) || (facing_sign > 0.0f && this.isKeyPressed(key_right)); f32 force = normalForce; if (pushing_in_facing_direction) { force = pushingForce; } this.AddForce(Vec2f(force * facing_sign , verticalForce)); } //bomb management bool hasItem(CBlob@ this, const string &in name) { CBitStream reqs, missing; AddRequirement(reqs, ""blob"", name, ""Bombs"", 1); CInventory@ inv = this.getInventory(); if (inv !is null) { return hasRequirements(inv, reqs, missing); } else { warn(""our inventory was null! KnightLogic.as""); } return false; } void TakeItem(CBlob@ this, const string &in name) { CBlob@ carried = this.getCarriedBlob(); if (carried !is null) { if (carried.getName() == name) { carried.server_Die(); return; } } CBitStream reqs, missing; AddRequirement(reqs, ""blob"", name, ""Bombs"", 1); CInventory@ inv = this.getInventory(); if (inv !is null) { if (hasRequirements(inv, reqs, missing)) { server_TakeRequirements(inv, reqs); } else { warn(""took a bomb even though we dont have one! KnightLogic.as""); } } else { warn(""our inventory was null! KnightLogic.as""); } } void onHitBlob(CBlob@ this, Vec2f worldPoint, Vec2f velocity, f32 damage, CBlob@ hitBlob, u8 customData) { KnightInfo@ knight; if (!this.get(""knightInfo"", @knight)) { return; } if (customData == Hitters::sword && ( //is a jab - note we dont have the dmg in here at the moment :/ knight.state == KnightStates::sword_cut_mid || knight.state == KnightStates::sword_cut_mid_down || knight.state == KnightStates::sword_cut_up || knight.state == KnightStates::sword_cut_down ) && blockAttack(hitBlob, velocity, 0.0f)) { this.getSprite().PlaySound(""/Stun"", 1.0f, this.getSexNum() == 0 ? 1.0f : 1.5f); setKnocked(this, 30, true); } if (customData == Hitters::shield) { setKnocked(hitBlob, 20, true); this.getSprite().PlaySound(""/Stun"", 1.0f, this.getSexNum() == 0 ? 1.0f : 1.5f); } } // bomb pick menu void onCreateInventoryMenu(CBlob@ this, CBlob@ forBlob, CGridMenu @gridmenu) { if (bombTypeNames.length == 0) { return; } this.ClearGridMenusExceptInventory(); Vec2f pos(gridmenu.getUpperLeftPosition().x + 0.5f * (gridmenu.getLowerRightPosition().x - gridmenu.getUpperLeftPosition().x), gridmenu.getUpperLeftPosition().y - 32 * 1 - 2 * 24); CGridMenu@ menu = CreateGridMenu(pos, this, Vec2f(bombTypeNames.length, 2), getTranslatedString(""Current bomb"")); u8 weaponSel = this.get_u8(""bomb type""); if (menu !is null) { menu.deleteAfterClick = false; for (uint i = 0; i < bombTypeNames.length; i++) { string matname = bombTypeNames[i]; CGridButton @button = menu.AddButton(bombIcons[i], getTranslatedString(bombNames[i]), this.getCommandID(""pick "" + matname)); if (button !is null) { bool enabled = this.getBlobCount(bombTypeNames[i]) > 0; button.SetEnabled(enabled); button.selectOneOnClick = true; if (weaponSel == i) { button.SetSelected(1); } } } } } void onAttach(CBlob@ this, CBlob@ attached, AttachmentPoint @ap) { for (uint i = 0; i < bombTypeNames.length; i++) { if (attached.getName() == bombTypeNames[i]) { this.set_u8(""bomb type"", i); break; } } if (!ap.socket) { KnightInfo@ knight; if (!this.get(""knightInfo"", @knight)) { return; } knight.state = KnightStates::normal; //cancel any attacks or shielding knight.swordTimer = 0; knight.doubleslash = false; this.set_s32(""currentKnightState"", 0); } } void onAddToInventory(CBlob@ this, CBlob@ blob) { const string itemname = blob.getName(); if (this.isMyPlayer() && this.getInventory().getItemsCount() > 1) { for (uint j = 1; j < bombTypeNames.length; j++) { if (itemname == bombTypeNames[j]) { SetHelp(this, ""help inventory"", ""knight"", ""$Help_Bomb1$$Swap$$Help_Bomb2$ $KEY_TAP$$KEY_F$"", """", 2); break; } } } if (this.getInventory().getItemsCount() == 0 || itemname == ""mat_bombs"") { for (uint j = 0; j < bombTypeNames.length; j++) { if (itemname == bombTypeNames[j]) { this.set_u8(""bomb type"", j); return; } } } } void SetFirstAvailableBomb(CBlob@ this) { u8 type = 255; if (this.exists(""bomb type"")) type = this.get_u8(""bomb type""); CInventory@ inv = this.getInventory(); bool typeReal = (uint(type) < bombTypeNames.length); if (typeReal && inv.getItem(bombTypeNames[type]) !is null) return; for (int i = 0; i < inv.getItemsCount(); i++) { const string itemname = inv.getItem(i).getName(); for (uint j = 0; j < bombTypeNames.length; j++) { if (itemname == bombTypeNames[j]) { type = j; break; } } if (type != 255) break; } this.set_u8(""bomb type"", type); } // Blame Fuzzle. bool canHit(CBlob@ this, CBlob@ b) { if (b.hasTag(""invincible"")) return false; // Don't hit temp blobs and items carried by teammates. if (b.isAttached()) { CBlob@ carrier = b.getCarriedBlob(); if (carrier !is null) if (carrier.hasTag(""player"") && (this.getTeamNum() == carrier.getTeamNum() || b.hasTag(""temp blob""))) return false; } if (b.hasTag(""dead"")) return true; return b.getTeamNum() != this.getTeamNum(); } ",12272,False,2363.5371435127167,median "{-# OPTIONS --cubical --no-import-sorts --safe --experimental-lossy-unification #-} module Cubical.ZCohomology.GroupStructure where open import Cubical.ZCohomology.Base open import Cubical.HITs.S1 open import Cubical.HITs.Sn open import Cubical.Foundations.HLevels open import Cubical.Foundations.Function open import Cubical.Foundations.Equiv open import Cubical.Foundations.Prelude open import Cubical.Foundations.Pointed open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.GroupoidLaws renaming (assoc to assoc∙) open import Cubical.Data.Sigma open import Cubical.HITs.Susp open import Cubical.HITs.SetTruncation renaming (rec to sRec ; rec2 to sRec2 ; elim to sElim ; elim2 to sElim2 ; setTruncIsSet to §) open import Cubical.Data.Int hiding (-_) renaming (_+_ to _ℤ+_) open import Cubical.Data.Nat renaming (+-assoc to +-assocℕ ; +-comm to +-commℕ) open import Cubical.HITs.Truncation renaming (elim to trElim ; map to trMap ; rec to trRec ; elim3 to trElim3 ; map2 to trMap2) open import Cubical.Homotopy.Loopspace open import Cubical.Algebra.Group open import Cubical.Algebra.AbGroup open import Cubical.Algebra.Semigroup open import Cubical.Algebra.Monoid open Iso renaming (inv to inv') private variable ℓ ℓ' : Level A : Type ℓ B : Type ℓ' A' : Pointed ℓ infixr 34 _+ₖ_ infixr 34 _+ₕ_ infixr 34 _+ₕ∙_ -- Addition in the Eilenberg-Maclane spaces is uniquely determined if we require it to have left- and right-unit laws, -- such that these agree on 0. In particular, any h-structure (see http://ericfinster.github.io/files/emhott.pdf) is unique. +ₖ-unique : (n : ℕ) → (comp1 comp2 : coHomK (suc n) → coHomK (suc n) → coHomK (suc n)) → (rUnit1 : (x : _) → comp1 x (coHom-pt (suc n)) ≡ x) → (lUnit1 : (x : _) → comp1 (coHom-pt (suc n)) x ≡ x) → (rUnit2 : (x : _) → comp2 x (coHom-pt (suc n)) ≡ x) → (lUnit2 : (x : _) → comp2 (coHom-pt (suc n)) x ≡ x) → (unId1 : rUnit1 (coHom-pt (suc n)) ≡ lUnit1 (coHom-pt (suc n))) → (unId2 : rUnit2 (coHom-pt (suc n)) ≡ lUnit2 (coHom-pt (suc n))) → (x y : _) → comp1 x y ≡ comp2 x y +ₖ-unique n comp1 comp2 rUnit1 lUnit1 rUnit2 lUnit2 unId1 unId2 = elim2 (λ _ _ → isOfHLevelPath (3 + n) (isOfHLevelTrunc (3 + n)) _ _) (wedgeConSn _ _ (λ _ _ → help _ _) (λ x → lUnit1 ∣ x ∣ ∙ sym (lUnit2 ∣ x ∣)) (λ x → rUnit1 ∣ x ∣ ∙ sym (rUnit2 ∣ x ∣)) (cong₂ _∙_ unId1 (cong sym unId2)) .fst) where help : isOfHLevel (2 + (n + suc n)) (coHomK (suc n)) help = subst (λ x → isOfHLevel x (coHomK (suc n))) (+-suc n (2 + n) ∙ +-suc (suc n) (suc n)) (isOfHLevelPlus n (isOfHLevelTrunc (3 + n))) wedgeConHLev : (n : ℕ) → isOfHLevel ((2 + n) + (2 + n)) (coHomK (2 + n)) wedgeConHLev n = subst (λ x → isOfHLevel x (coHomK (2 + n))) (sym (+-suc (2 + n) (suc n) ∙ +-suc (3 + n) n)) (isOfHLevelPlus' {n = n} (4 + n) (isOfHLevelTrunc (4 + n))) wedgeConHLev' : (n : ℕ) → isOfHLevel ((2 + n) + (2 + n)) (typ (Ω (coHomK-ptd (3 + n)))) wedgeConHLev' n = subst (λ x → isOfHLevel x (typ (Ω (coHomK-ptd (3 + n))))) (sym (+-suc (2 + n) (suc n) ∙ +-suc (3 + n) n)) (isOfHLevelPlus' {n = n} (4 + n) (isOfHLevelTrunc (5 + n) _ _)) wedgeConHLevPath : (n : ℕ) → (x y : coHomK (suc n)) → isOfHLevel ((suc n) + (suc n)) (x ≡ y) wedgeConHLevPath zero x y = isOfHLevelTrunc 3 _ _ wedgeConHLevPath (suc n) x y = isOfHLevelPath ((2 + n) + (2 + n)) (wedgeConHLev n) _ _ -- addition for n ≥ 2 together with the left- and right-unit laws (modulo truncations) preAdd : (n : ℕ) → Σ[ f ∈ (S₊ (2 + n) → S₊ (2 + n) → coHomK (2 + n)) ] ((x : S₊ (2 + n)) → f north x ≡ ∣ x ∣) × ((x : S₊ (2 + n)) → f x north ≡ ∣ x ∣) preAdd n = wedgeConSn _ _ (λ _ _ → wedgeConHLev n) ∣_∣ ∣_∣ refl -- addition for n = 1 wedgeMapS¹ : S¹ → S¹ → S¹ wedgeMapS¹ base y = y wedgeMapS¹ (loop i) base = loop i wedgeMapS¹ (loop i) (loop j) = hcomp (λ k → λ { (i = i0) → loop j ; (i = i1) → loop (j ∧ k) ; (j = i0) → loop i ; (j = i1) → loop (i ∧ k)}) (loop (i ∨ j)) ---------- Algebra/Group stuff -------- 0ₖ : (n : ℕ) → coHomK n 0ₖ = coHom-pt _+ₖ_ : {n : ℕ} → coHomK n → coHomK n → coHomK n _+ₖ_ {n = zero} x y = x ℤ+ y _+ₖ_ {n = suc zero} = trMap2 wedgeMapS¹ _+ₖ_ {n = suc (suc n)} = trRec (isOfHLevelΠ (4 + n) λ _ → isOfHLevelTrunc (4 + n)) λ x → trRec (isOfHLevelTrunc (4 + n)) λ y → preAdd n .fst x y private isEquiv+ : (n : ℕ) → (x : coHomK (suc n)) → isEquiv (_+ₖ_ {n = (suc n)} x) isEquiv+ zero = trElim (λ _ → isProp→isOfHLevelSuc 2 (isPropIsEquiv _)) (toPropElim (λ _ → isPropIsEquiv _) (subst isEquiv (sym help) (idIsEquiv _))) where help : _+ₖ_ {n = 1} (coHom-pt 1) ≡ idfun _ help = funExt (trElim (λ _ → isOfHLevelPath 3 (isOfHLevelTrunc 3) _ _) λ _ → refl) isEquiv+ (suc n) = trElim (λ _ → isProp→isOfHLevelSuc (3 + n) (isPropIsEquiv _)) (suspToPropElim (ptSn (suc n)) (λ _ → isPropIsEquiv _) (subst isEquiv (sym help) (idIsEquiv _))) where help : _+ₖ_ {n = (2 + n)} (coHom-pt (2 + n)) ≡ idfun _ help = funExt (trElim (λ _ → isOfHLevelPath (4 + n) (isOfHLevelTrunc (4 + n)) _ _) λ _ → refl) Kₙ≃Kₙ : (n : ℕ) (x : coHomK (suc n)) → coHomK (suc n) ≃ coHomK (suc n) Kₙ≃Kₙ n x = _ , isEquiv+ n x -ₖ_ : {n : ℕ} → coHomK n → coHomK n -ₖ_ {n = zero} x = 0 - x -ₖ_ {n = suc n} x = invEq (Kₙ≃Kₙ n x) (coHom-pt (suc n)) _-ₖ_ : {n : ℕ} → coHomK n → coHomK n → coHomK n _-ₖ_ {n = n} x y = _+ₖ_ {n = n} x (-ₖ_ {n = n} y) +ₖ-syntax : (n : ℕ) → coHomK n → coHomK n → coHomK n +ₖ-syntax n = _+ₖ_ {n = n} -ₖ-syntax : (n : ℕ) → coHomK n → coHomK n -ₖ-syntax n = -ₖ_ {n = n} -'ₖ-syntax : (n : ℕ) → coHomK n → coHomK n → coHomK n -'ₖ-syntax n = _-ₖ_ {n = n} syntax +ₖ-syntax n x y = x +[ n ]ₖ y syntax -ₖ-syntax n x = -[ n ]ₖ x syntax -'ₖ-syntax n x y = x -[ n ]ₖ y ------- Groupoid Laws for Kₙ --------- commₖ : (n : ℕ) → (x y : coHomK n) → x +[ n ]ₖ y ≡ y +[ n ]ₖ x commₖ zero = +-comm commₖ (suc zero) = elim2 (λ _ _ → isOfHLevelPath 3 (isOfHLevelTrunc 3) _ _) (wedgeConSn _ _ (λ _ _ → isOfHLevelTrunc 3 _ _) (λ {base → refl ; (loop i) → refl}) (λ {base → refl ; (loop i) → refl}) refl .fst) commₖ (suc (suc n)) = elim2 (λ _ _ → isOfHLevelPath (4 + n) (isOfHLevelTrunc (4 + n)) _ _) (wedgeConSn _ _ (λ x y → isOfHLevelPath ((2 + n) + (2 + n)) (wedgeConHLev n) _ _) (λ x → preAdd n .snd .fst x ∙ sym (preAdd n .snd .snd x)) (λ x → preAdd n .snd .snd x ∙ sym (preAdd n .snd .fst x)) refl .fst) commₖ-base : (n : ℕ) → commₖ n (coHom-pt n) (coHom-pt n) ≡ refl commₖ-base zero = refl commₖ-base (suc zero) = refl commₖ-base (suc (suc n)) = sym (rUnit _) rCancelₖ : (n : ℕ) → (x : coHomK n) → x -[ n ]ₖ x ≡ coHom-pt n rCancelₖ zero x = +-comm x (pos 0 - x) ∙ minusPlus x 0 rCancelₖ (suc n) x = retEq (Kₙ≃Kₙ n x) (coHom-pt _) lCancelₖ : (n : ℕ) → (x : coHomK n) → (-[ n ]ₖ x) +[ n ]ₖ x ≡ coHom-pt n lCancelₖ zero x = minusPlus x 0 lCancelₖ (suc n) x = commₖ (suc n) _ _ ∙ rCancelₖ (suc n) x rUnitₖ : (n : ℕ) → (x : coHomK n) → x +[ n ]ₖ coHom-pt n ≡ x rUnitₖ zero x = refl rUnitₖ (suc zero) = trElim (λ _ → isOfHLevelPath 3 (isOfHLevelTrunc 3) _ _) λ {base → refl ; (loop i) → refl} rUnitₖ (suc (suc n)) = trElim (λ _ → isOfHLevelPath (4 + n) (isOfHLevelTrunc (4 + n)) _ _) λ x → preAdd n .snd .snd x lUnitₖ : (n : ℕ) → (x : coHomK n) → coHom-pt n +[ n ]ₖ x ≡ x lUnitₖ zero x = sym (pos0+ x) lUnitₖ (suc zero) = trElim (λ _ → isOfHLevelPath 3 (isOfHLevelTrunc 3) _ _) λ {base → refl ; (loop i) → refl} lUnitₖ (suc (suc n)) = trElim (λ _ → isOfHLevelPath (4 + n) (isOfHLevelTrunc (4 + n)) _ _) λ x → refl assocₖ : (n : ℕ) → (x y z : coHomK n) → x +[ n ]ₖ (y +[ n ]ₖ z) ≡ (x +[ n ]ₖ y) +[ n ]ₖ z assocₖ zero = +-assoc assocₖ (suc zero) = trElim3 (λ _ _ _ → isOfHLevelPath 3 (isOfHLevelTrunc 3) _ _) λ x → wedgeConSn _ _ (λ _ _ → isOfHLevelTrunc 3 _ _) (λ y i → rUnitₖ 1 ∣ x ∣ (~ i) +ₖ ∣ y ∣) (λ z → cong (∣ x ∣ +ₖ_) (rUnitₖ 1 ∣ z ∣) ∙ sym (rUnitₖ 1 (∣ x ∣ +ₖ ∣ z ∣))) (helper x) .fst where helper : (x : S¹) → cong (∣ x ∣ +ₖ_) (rUnitₖ 1 ∣ base ∣) ∙ sym (rUnitₖ 1 (∣ x ∣ +ₖ ∣ base ∣)) ≡ (cong (_+ₖ ∣ base ∣) (sym (rUnitₖ 1 ∣ x ∣))) helper = toPropElim (λ _ → isOfHLevelTrunc 3 _ _ _ _) (sym (lUnit refl)) assocₖ (suc (suc n)) = trElim3 (λ _ _ _ → isOfHLevelPath (4 + n) (isOfHLevelTrunc (4 + n)) _ _) (wedgeConSn-×3 _ (λ x z i → preAdd n .snd .snd x (~ i) +ₖ ∣ z ∣) (λ x y → cong (∣ x ∣ +ₖ_) (rUnitₖ (2 + n) ∣ y ∣) ∙ sym (rUnitₖ (2 + n) (∣ x ∣ +ₖ ∣ y ∣))) (lUnit (sym (rUnitₖ (2 + n) (∣ north ∣ +ₖ ∣ north ∣))))) where wedgeConSn-×3 : (n : ℕ) → (f : (x z : S₊ (2 + n))→ ∣ x ∣ +ₖ ((0ₖ _) +ₖ ∣ z ∣) ≡ (∣ x ∣ +ₖ (0ₖ _)) +ₖ ∣ z ∣) → (g : (x y : S₊ (2 + n)) → ∣ x ∣ +ₖ (∣ y ∣ +ₖ 0ₖ _) ≡ (∣ x ∣ +ₖ ∣ y ∣) +ₖ 0ₖ _) → (f (ptSn _) (ptSn _) ≡ g (ptSn _) (ptSn _)) → (x y z : S₊ (2 + n)) → ∣ x ∣ +ₖ (∣ y ∣ +ₖ ∣ z ∣) ≡ (∣ x ∣ +ₖ ∣ y ∣) +ₖ ∣ z ∣ wedgeConSn-×3 n f g d x = wedgeConSn _ _ (λ _ _ → isOfHLevelPath ((2 + n) + (2 + n)) (wedgeConHLev n) _ _) (f x) (g x) (sphereElim _ {A = λ x → g x (ptSn (suc (suc n))) ≡ f x (ptSn (suc (suc n))) } (λ _ → isOfHLevelTrunc (4 + n) _ _ _ _) (sym d) x) .fst {- This was the original proof for the case n ≥ 2: For some reason it doesn't check in reasonable time anymore: assocₖ (suc (suc n)) = trElim3 (λ _ _ _ → isOfHLevelPath (4 + n) (isOfHLevelTrunc (4 + n)) _ _) λ x → wedgeConSn _ _ (λ _ _ → isOfHLevelPath ((2 + n) + (2 + n)) (wedgeConHLev n) _ _) (λ z i → preAdd n .snd .snd x (~ i) +ₖ ∣ z ∣) (λ y → cong (∣ x ∣ +ₖ_) (rUnitₖ (2 + n) ∣ y ∣) ∙ sym (rUnitₖ (2 + n) (∣ x ∣ +ₖ ∣ y ∣))) (helper x) .fst where helper : (x : S₊ (2 + n)) → cong (∣ x ∣ +ₖ_) (rUnitₖ (2 + n) ∣ north ∣) ∙ sym (rUnitₖ (2 + n) (∣ x ∣ +ₖ ∣ north ∣)) ≡ cong (_+ₖ ∣ north ∣) (sym (preAdd n .snd .snd x)) helper = sphereElim (suc n) (λ _ → isOfHLevelTrunc (4 + n) _ _ _ _) (sym (lUnit (sym (rUnitₖ (2 + n) (∣ north ∣ +ₖ ∣ north ∣))))) -} lUnitₖ≡rUnitₖ : (n : ℕ) → lUnitₖ n (coHom-pt n) ≡ rUnitₖ n (coHom-pt n) lUnitₖ≡rUnitₖ zero = isSetInt _ _ _ _ lUnitₖ≡rUnitₖ (suc zero) = refl lUnitₖ≡rUnitₖ (suc (suc n)) = refl ------ Commutativity of ΩKₙ -- We show that p ∙ q ≡ (λ i → (p i) +ₖ (q i)) for any p q : ΩKₙ₊₁. This allows us to prove that p ∙ q ≡ q ∙ p -- without having to use the equivalence Kₙ ≃ ΩKₙ₊₁ ∙≡+₁ : (p q : typ (Ω (coHomK-ptd 1))) → p ∙ q ≡ cong₂ _+ₖ_ p q ∙≡+₁ p q = (λ i → (λ j → rUnitₖ 1 (p j) (~ i)) ∙ λ j → lUnitₖ 1 (q j) (~ i)) ∙ sym (cong₂Funct _+ₖ_ p q) ∙≡+₂ : (n : ℕ) (p q : typ (Ω (coHomK-ptd (suc (suc n))))) → p ∙ q ≡ cong₂ _+ₖ_ p q ∙≡+₂ n p q = (λ i → (λ j → rUnitₖ (2 + n) (p j) (~ i)) ∙ λ j → lUnitₖ (2 + n) (q j) (~ i)) ∙ sym (cong₂Funct _+ₖ_ p q) cong+ₖ-comm : (n : ℕ) (p q : typ (Ω (coHomK-ptd (suc n)))) → cong₂ _+ₖ_ p q ≡ cong₂ _+ₖ_ q p cong+ₖ-comm zero p q = rUnit (cong₂ _+ₖ_ p q) ∙∙ (λ i → (λ j → commₖ 1 ∣ base ∣ ∣ base ∣ (i ∧ j)) ∙∙ (λ j → commₖ 1 (p j) (q j) i) ∙∙ λ j → commₖ 1 ∣ base ∣ ∣ base ∣ (i ∧ ~ j)) ∙∙ ((λ i → commₖ-base 1 i ∙∙ cong₂ _+ₖ_ q p ∙∙ sym (commₖ-base 1 i)) ∙ sym (rUnit (cong₂ _+ₖ_ q p))) cong+ₖ-comm (suc n) p q = rUnit (cong₂ _+ₖ_ p q) ∙∙ (λ i → (λ j → commₖ (2 + n) ∣ north ∣ ∣ north ∣ (i ∧ j)) ∙∙ (λ j → commₖ (2 + n) (p j) (q j) i ) ∙∙ λ j → commₖ (2 + n) ∣ north ∣ ∣ north ∣ (i ∧ ~ j)) ∙∙ ((λ i → commₖ-base (2 + n) i ∙∙ cong₂ _+ₖ_ q p ∙∙ sym (commₖ-base (2 + n) i)) ∙ sym (rUnit (cong₂ _+ₖ_ q p))) isCommΩK : (n : ℕ) → isComm∙ (coHomK-ptd n) isCommΩK zero p q = isSetInt _ _ (p ∙ q) (q ∙ p) isCommΩK (suc zero) p q = ∙≡+₁ p q ∙∙ cong+ₖ-comm 0 p q ∙∙ sym (∙≡+₁ q p) isCommΩK (suc (suc n)) p q = ∙≡+₂ n p q ∙∙ cong+ₖ-comm (suc n) p q ∙∙ sym (∙≡+₂ n q p) ----- some other useful lemmas about algebra in Kₙ -0ₖ : {n : ℕ} → -[ n ]ₖ (0ₖ n) ≡ (0ₖ n) -0ₖ {n = zero} = refl -0ₖ {n = suc zero} = refl -0ₖ {n = suc (suc n)} = refl -distrₖ : (n : ℕ) (x y : coHomK n) → -[ n ]ₖ (x +[ n ]ₖ y) ≡ (-[ n ]ₖ x) +[ n ]ₖ (-[ n ]ₖ y) -distrₖ zero x y = GroupLemmas.invDistr intGroup x y ∙ +-comm (0 - y) (0 - x) -distrₖ (suc zero) = elim2 (λ _ _ → isOfHLevelPath 3 (isOfHLevelTrunc 3) _ _) (wedgeConSn _ _ (λ _ _ → isOfHLevelTrunc 3 _ _) (λ x → sym (lUnitₖ 1 (-[ 1 ]ₖ ∣ x ∣))) (λ x → cong (λ x → -[ 1 ]ₖ x) (rUnitₖ 1 ∣ x ∣) ∙ sym (rUnitₖ 1 (-[ 1 ]ₖ ∣ x ∣))) (sym (rUnit refl)) .fst) -distrₖ (suc (suc n)) = elim2 (λ _ _ → isOfHLevelPath (4 + n) (isOfHLevelTrunc (4 + n)) _ _) (wedgeConSn _ _ (λ _ _ → isOfHLevelPath ((2 + n) + (2 + n)) (wedgeConHLev n) _ _) (λ x → sym (lUnitₖ (2 + n) (-[ (2 + n) ]ₖ ∣ x ∣))) (λ x → cong (λ x → -[ (2 + n) ]ₖ x) (rUnitₖ (2 + n) ∣ x ∣ ) ∙ sym (rUnitₖ (2 + n) (-[ (2 + n) ]ₖ ∣ x ∣))) (sym (rUnit refl)) .fst) -cancelRₖ : (n : ℕ) (x y : coHomK n) → (y +[ n ]ₖ x) -[ n ]ₖ x ≡ y -cancelRₖ zero x y = sym (+-assoc y x (0 - x)) ∙∙ cong (y ℤ+_) (+-comm x (0 - x)) ∙∙ cong (y ℤ+_) (minusPlus x (pos 0)) -cancelRₖ (suc zero) = elim2 (λ _ _ → isOfHLevelPath 3 (isOfHLevelTrunc 3) _ _) (wedgeConSn _ _ (λ _ _ → wedgeConHLevPath 0 _ _) (λ x → cong (_+ₖ ∣ base ∣) (rUnitₖ 1 ∣ x ∣) ∙ rUnitₖ 1 ∣ x ∣) (λ x → rCancelₖ 1 ∣ x ∣) (transportRefl refl ∙ rUnit refl) .fst) -cancelRₖ (suc (suc n)) = elim2 (λ _ _ → isOfHLevelPath (4 + n) (isOfHLevelTrunc (4 + n)) _ _) (wedgeConSn _ _ (λ _ _ → wedgeConHLevPath (suc n) _ _) (λ x → cong (_+ₖ ∣ north ∣) (rUnitₖ (2 + n) ∣ x ∣) ∙ rUnitₖ (2 + n) ∣ x ∣) (λ x → rCancelₖ (2 + n) ∣ x ∣) (transportRefl refl ∙ rUnit refl) .fst) -cancelLₖ : (n : ℕ) (x y : coHomK n) → (x +[ n ]ₖ y) -[ n ]ₖ x ≡ y -cancelLₖ n x y = cong (λ z → z -[ n ]ₖ x) (commₖ n x y) ∙ -cancelRₖ n x y -+cancelₖ : (n : ℕ) (x y : coHomK n) → (x -[ n ]ₖ y) +[ n ]ₖ y ≡ x -+cancelₖ zero x y = sym (+-assoc x (0 - y) y) ∙ cong (x ℤ+_) (minusPlus y (pos 0)) -+cancelₖ (suc zero) = elim2 (λ _ _ → isOfHLevelPath 3 (isOfHLevelTrunc 3) _ _) (wedgeConSn _ _ (λ _ _ → wedgeConHLevPath 0 _ _) (λ x → cong (_+ₖ ∣ x ∣) (lUnitₖ 1 (-ₖ ∣ x ∣)) ∙ lCancelₖ 1 ∣ x ∣) (λ x → cong (_+ₖ ∣ base ∣) (rUnitₖ 1 ∣ x ∣) ∙ rUnitₖ 1 ∣ x ∣) ((λ i → refl ∙ (transportRefl refl (~ i))) ∙ lUnit _) .fst) -+cancelₖ (suc (suc n)) = elim2 (λ _ _ → isOfHLevelPath (4 + n) (isOfHLevelTrunc (4 + n)) _ _) (wedgeConSn _ _ (λ _ _ → wedgeConHLevPath (suc n) _ _) (λ x → cong (_+ₖ ∣ x ∣) (lUnitₖ (2 + n) (-ₖ ∣ x ∣)) ∙ lCancelₖ (2 + n) ∣ x ∣) (λ x → cong (_+ₖ ∣ north ∣) (rUnitₖ (2 + n) ∣ x ∣) ∙ rUnitₖ (2 + n) ∣ x ∣) (cong (refl ∙_) (rUnit refl ∙ (λ i → rUnit refl i ∙ transportRefl refl (~ i)))) .fst) ---- Group structure of cohomology groups _+ₕ_ : {n : ℕ} → coHom n A → coHom n A → coHom n A _+ₕ_ {n = n} = sRec2 § λ a b → ∣ (λ x → a x +[ n ]ₖ b x) ∣₂ -ₕ_ : {n : ℕ} → coHom n A → coHom n A -ₕ_ {n = n} = sRec § λ a → ∣ (λ x → -[ n ]ₖ a x) ∣₂ _-ₕ_ : {n : ℕ} → coHom n A → coHom n A → coHom n A _-ₕ_ {n = n} = sRec2 § λ a b → ∣ (λ x → a x -[ n ]ₖ b x) ∣₂ +ₕ-syntax : (n : ℕ) → coHom n A → coHom n A → coHom n A +ₕ-syntax n = _+ₕ_ {n = n} -ₕ-syntax : (n : ℕ) → coHom n A → coHom n A -ₕ-syntax n = -ₕ_ {n = n} -ₕ'-syntax : (n : ℕ) → coHom n A → coHom n A → coHom n A -ₕ'-syntax n = _-ₕ_ {n = n} syntax +ₕ-syntax n x y = x +[ n ]ₕ y syntax -ₕ-syntax n x = -[ n ]ₕ x syntax -ₕ'-syntax n x y = x -[ n ]ₕ y 0ₕ : (n : ℕ) → coHom n A 0ₕ n = ∣ (λ _ → (0ₖ n)) ∣₂ rUnitₕ : (n : ℕ) (x : coHom n A) → x +[ n ]ₕ (0ₕ n) ≡ x rUnitₕ n = sElim (λ _ → isOfHLevelPath 1 (§ _ _)) λ a i → ∣ funExt (λ x → rUnitₖ n (a x)) i ∣₂ lUnitₕ : (n : ℕ) (x : coHom n A) → (0ₕ n) +[ n ]ₕ x ≡ x lUnitₕ n = sElim (λ _ → isOfHLevelPath 1 (§ _ _)) λ a i → ∣ funExt (λ x → lUnitₖ n (a x)) i ∣₂ rCancelₕ : (n : ℕ) (x : coHom n A) → x +[ n ]ₕ (-[ n ]ₕ x) ≡ 0ₕ n rCancelₕ n = sElim (λ _ → isOfHLevelPath 1 (§ _ _)) λ a i → ∣ funExt (λ x → rCancelₖ n (a x)) i ∣₂ lCancelₕ : (n : ℕ) (x : coHom n A) → (-[ n ]ₕ x) +[ n ]ₕ x ≡ 0ₕ n lCancelₕ n = sElim (λ _ → isOfHLevelPath 1 (§ _ _)) λ a i → ∣ funExt (λ x → lCancelₖ n (a x)) i ∣₂ assocₕ : (n : ℕ) (x y z : coHom n A) → (x +[ n ]ₕ (y +[ n ]ₕ z)) ≡ ((x +[ n ]ₕ y) +[ n ]ₕ z) assocₕ n = elim3 (λ _ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b c i → ∣ funExt (λ x → assocₖ n (a x) (b x) (c x)) i ∣₂ commₕ : (n : ℕ) (x y : coHom n A) → (x +[ n ]ₕ y) ≡ (y +[ n ]ₕ x) commₕ n = sElim2 (λ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b i → ∣ funExt (λ x → commₖ n (a x) (b x)) i ∣₂ -cancelLₕ : (n : ℕ) (x y : coHom n A) → (x +[ n ]ₕ y) -[ n ]ₕ x ≡ y -cancelLₕ n = sElim2 (λ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b i → ∣ (λ x → -cancelLₖ n (a x) (b x) i) ∣₂ -cancelRₕ : (n : ℕ) (x y : coHom n A) → (y +[ n ]ₕ x) -[ n ]ₕ x ≡ y -cancelRₕ n = sElim2 (λ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b i → ∣ (λ x → -cancelRₖ n (a x) (b x) i) ∣₂ -+cancelₕ : (n : ℕ) (x y : coHom n A) → (x -[ n ]ₕ y) +[ n ]ₕ y ≡ x -+cancelₕ n = sElim2 (λ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b i → ∣ (λ x → -+cancelₖ n (a x) (b x) i) ∣₂ -- Group structure of reduced cohomology groups (in progress - might need K to compute properly first) _+ₕ∙_ : {A : Pointed ℓ} {n : ℕ} → coHomRed n A → coHomRed n A → coHomRed n A _+ₕ∙_ {n = zero} = sRec2 § λ { (a , pa) (b , pb) → ∣ (λ x → a x +[ zero ]ₖ b x) , (λ i → (pa i +[ zero ]ₖ pb i)) ∣₂ } _+ₕ∙_ {n = (suc zero)} = sRec2 § λ { (a , pa) (b , pb) → ∣ (λ x → a x +[ 1 ]ₖ b x) , (λ i → pa i +[ 1 ]ₖ pb i) ∣₂ } _+ₕ∙_ {n = (suc (suc n))} = sRec2 § λ { (a , pa) (b , pb) → ∣ (λ x → a x +[ (2 + n) ]ₖ b x) , (λ i → pa i +[ (2 + n) ]ₖ pb i) ∣₂ } -ₕ∙_ : {A : Pointed ℓ} {n : ℕ} → coHomRed n A → coHomRed n A -ₕ∙_ {n = zero} = sRec § λ {(f , p) → ∣ (λ x → -[ 0 ]ₖ (f x)) , cong (λ x → -[ 0 ]ₖ x) p ∣₂} -ₕ∙_ {n = suc zero} = sRec § λ {(f , p) → ∣ (λ x → -ₖ (f x)) , cong -ₖ_ p ∣₂} -ₕ∙_ {n = suc (suc n)} = sRec § λ {(f , p) → ∣ (λ x → -ₖ (f x)) , cong -ₖ_ p ∣₂} 0ₕ∙ : {A : Pointed ℓ} (n : ℕ) → coHomRed n A 0ₕ∙ n = ∣ (λ _ → 0ₖ n) , refl ∣₂ +ₕ∙-syntax : {A : Pointed ℓ} (n : ℕ) → coHomRed n A → coHomRed n A → coHomRed n A +ₕ∙-syntax n = _+ₕ∙_ {n = n} -ₕ∙-syntax : {A : Pointed ℓ} (n : ℕ) → coHomRed n A → coHomRed n A -ₕ∙-syntax n = -ₕ∙_ {n = n} -'ₕ∙-syntax : {A : Pointed ℓ} (n : ℕ) → coHomRed n A → coHomRed n A → coHomRed n A -'ₕ∙-syntax n x y = _+ₕ∙_ {n = n} x (-ₕ∙_ {n = n} y) syntax +ₕ∙-syntax n x y = x +[ n ]ₕ∙ y syntax -ₕ∙-syntax n x = -[ n ]ₕ∙ x syntax -'ₕ∙-syntax n x y = x -[ n ]ₕ∙ y commₕ∙ : {A : Pointed ℓ} (n : ℕ) (x y : coHomRed n A) → x +[ n ]ₕ∙ y ≡ y +[ n ]ₕ∙ x commₕ∙ zero = sElim2 (λ _ _ → isOfHLevelPath 2 § _ _) λ {(f , p) (g , q) → cong ∣_∣₂ (Σ≡Prop (λ _ → isSetInt _ _) λ i x → commₖ 0 (f x) (g x) i)} commₕ∙ (suc zero) = sElim2 (λ _ _ → isOfHLevelPath 2 § _ _) λ {(f , p) (g , q) → cong ∣_∣₂ (ΣPathP ((λ i x → commₖ 1 (f x) (g x) i) , λ i j → commₖ 1 (p j) (q j) i))} commₕ∙ {A = A} (suc (suc n)) = sElim2 (λ _ _ → isOfHLevelPath 2 § _ _) λ {(f , p) (g , q) → cong ∣_∣₂ (ΣPathP ((λ i x → commₖ (2 + n) (f x) (g x) i) , λ i j → hcomp (λ k → λ {(i = i0) → p j +ₖ q j ; (i = i1) → q j +ₖ p j ; (j = i0) → commₖ (2 + n) (f (pt A)) (g (pt A)) i ; (j = i1) → rUnit (refl {x = 0ₖ (2 + n)}) (~ k) i}) (commₖ (2 + n) (p j) (q j) i)))} rUnitₕ∙ : {A : Pointed ℓ} (n : ℕ) (x : coHomRed n A) → x +[ n ]ₕ∙ 0ₕ∙ n ≡ x rUnitₕ∙ zero = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (Σ≡Prop (λ _ → isSetInt _ _) λ i x → rUnitₖ zero (f x) i)} rUnitₕ∙ (suc zero) = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (ΣPathP ((λ i x → rUnitₖ 1 (f x) i) , λ i j → rUnitₖ 1 (p j) i))} rUnitₕ∙ (suc (suc n)) = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (ΣPathP ((λ i x → rUnitₖ (2 + n) (f x) i) , λ i j → rUnitₖ (2 + n) (p j) i))} lUnitₕ∙ : {A : Pointed ℓ} (n : ℕ) (x : coHomRed n A) → 0ₕ∙ n +[ n ]ₕ∙ x ≡ x lUnitₕ∙ zero = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (Σ≡Prop (λ _ → isSetInt _ _) λ i x → lUnitₖ zero (f x) i)} lUnitₕ∙ (suc zero) = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (ΣPathP ((λ i x → lUnitₖ 1 (f x) i) , λ i j → lUnitₖ 1 (p j) i))} lUnitₕ∙ (suc (suc n)) = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (ΣPathP ((λ i x → lUnitₖ (2 + n) (f x) i) , λ i j → lUnitₖ (2 + n) (p j) i))} rCancelₕ∙ : {A : Pointed ℓ} (n : ℕ) (x : coHomRed n A) → x +[ n ]ₕ∙ (-[ n ]ₕ∙ x) ≡ 0ₕ∙ n rCancelₕ∙ zero = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (Σ≡Prop (λ _ → isSetInt _ _) λ i x → rCancelₖ zero (f x) i)} rCancelₕ∙ {A = A} (suc zero) = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (ΣPathP ((λ i x → rCancelₖ 1 (f x) i) , λ i j → hcomp (λ k → λ { (i = i0) → p j +ₖ (-ₖ p j) ; (i = i1) → 0ₖ 1 ; (j = i0) → rCancelₖ 1 (f (pt A)) i ; (j = i1) → transportRefl (refl {x = 0ₖ 1}) k i}) (rCancelₖ 1 (p j) i)))} rCancelₕ∙ {A = A} (suc (suc n)) = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (ΣPathP ((λ i x → rCancelₖ (2 + n) (f x) i) , λ i j → hcomp (λ k → λ { (i = i0) → p j +ₖ (-ₖ p j) ; (i = i1) → 0ₖ (2 + n) ; (j = i0) → rCancelₖ (2 + n) (f (pt A)) i ; (j = i1) → transportRefl (refl {x = 0ₖ (2 + n)}) k i}) (rCancelₖ (2 + n) (p j) i)))} lCancel-refl : lCancelₖ 1 (0ₖ _) ≡ refl lCancel-refl = (λ i → refl ∙ transportRefl refl i) ∙ sym (rUnit refl) lCancelₕ∙ : {A : Pointed ℓ} (n : ℕ) (x : coHomRed n A) → (-[ n ]ₕ∙ x) +[ n ]ₕ∙ x ≡ 0ₕ∙ n lCancelₕ∙ zero = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (Σ≡Prop (λ _ → isSetInt _ _) λ i x → lCancelₖ zero (f x) i)} lCancelₕ∙ {A = A} (suc zero) = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (ΣPathP ((λ i x → lCancelₖ 1 (f x) i) , λ i j → hcomp (λ k → λ { (i = i0) → (-ₖ p j) +ₖ (p j) ; (i = i1) → 0ₖ 1 ; (j = i0) → lCancelₖ 1 (f (pt A)) i ; (j = i1) → ((λ i → refl {x = 0ₖ 1} ∙ transportRefl refl i) ∙ sym (rUnit refl)) k i}) (lCancelₖ 1 (p j) i)))} lCancelₕ∙ {A = A} (suc (suc n)) = sElim (λ _ → isOfHLevelPath 2 § _ _) λ {(f , p) → cong ∣_∣₂ (ΣPathP ((λ i x → lCancelₖ (2 + n) (f x) i) , λ i j → hcomp (λ k → λ { (i = i0) → (-ₖ p j) +ₖ (p j) ; (i = i1) → 0ₖ (2 + n) ; (j = i0) → lCancelₖ (2 + n) (f (pt A)) i ; (j = i1) → ((λ i → (rUnit refl (~ i)) ∙ (transportRefl (refl {x = 0ₖ (2 + n)}) i)) ∙ sym (rUnit refl)) k i}) (lCancelₖ (2 + n) (p j) i)))} assocₕ∙ : {A : Pointed ℓ} (n : ℕ) (x y z : coHomRed n A) → (x +[ n ]ₕ∙ (y +[ n ]ₕ∙ z)) ≡ ((x +[ n ]ₕ∙ y) +[ n ]ₕ∙ z) assocₕ∙ zero = elim3 (λ _ _ _ → isOfHLevelPath 2 § _ _) λ {(f , p) (g , q) (h , r) → cong ∣_∣₂ (Σ≡Prop (λ _ → isSetInt _ _) (λ i x → assocₖ zero (f x) (g x) (h x) i))} assocₕ∙ (suc zero) = elim3 (λ _ _ _ → isOfHLevelPath 2 § _ _) λ {(f , p) (g , q) (h , r) → cong ∣_∣₂ (ΣPathP ((λ i x → assocₖ 1 (f x) (g x) (h x) i) , λ i j → assocₖ 1 (p j) (q j) (r j) i))} assocₕ∙ (suc (suc n)) = elim3 (λ _ _ _ → isOfHLevelPath 2 § _ _) λ {(f , p) (g , q) (h , r) → cong ∣_∣₂ (ΣPathP ((λ i x → assocₖ (2 + n) (f x) (g x) (h x) i) , λ i j → assocₖ (2 + n) (p j) (q j) (r j) i))} open IsSemigroup open IsMonoid open GroupStr open GroupHom coHomGr : (n : ℕ) (A : Type ℓ) → Group {ℓ} coHomGr n A = coHom n A , coHomGrnA where coHomGrnA : GroupStr (coHom n A) 0g coHomGrnA = 0ₕ n GroupStr._+_ coHomGrnA = λ x y → x +[ n ]ₕ y - coHomGrnA = λ x → -[ n ]ₕ x isGroup coHomGrnA = helper where abstract helper : IsGroup {G = coHom n A} (0ₕ n) (λ x y → x +[ n ]ₕ y) (λ x → -[ n ]ₕ x) helper = makeIsGroup § (assocₕ n) (rUnitₕ n) (lUnitₕ n) (rCancelₕ n) (lCancelₕ n) ×coHomGr : (n : ℕ) (A : Type ℓ) (B : Type ℓ') → Group ×coHomGr n A B = dirProd (coHomGr n A) (coHomGr n B) coHomGroup : (n : ℕ) (A : Type ℓ) → AbGroup {ℓ} fst (coHomGroup n A) = coHom n A AbGroupStr.0g (snd (coHomGroup n A)) = 0ₕ n AbGroupStr._+_ (snd (coHomGroup n A)) = _+ₕ_ {n = n} AbGroupStr.- snd (coHomGroup n A) = -ₕ_ {n = n} IsAbGroup.isGroup (AbGroupStr.isAbGroup (snd (coHomGroup n A))) = isGroup (snd (coHomGr n A)) IsAbGroup.comm (AbGroupStr.isAbGroup (snd (coHomGroup n A))) = commₕ n -- Reduced cohomology group (direct def) coHomRedGroupDir : (n : ℕ) (A : Pointed ℓ) → AbGroup {ℓ} fst (coHomRedGroupDir n A) = coHomRed n A AbGroupStr.0g (snd (coHomRedGroupDir n A)) = 0ₕ∙ n AbGroupStr._+_ (snd (coHomRedGroupDir n A)) = _+ₕ∙_ {n = n} AbGroupStr.- snd (coHomRedGroupDir n A) = -ₕ∙_ {n = n} IsAbGroup.isGroup (AbGroupStr.isAbGroup (snd (coHomRedGroupDir n A))) = helper where abstract helper : IsGroup {G = coHomRed n A} (0ₕ∙ n) (_+ₕ∙_ {n = n}) (-ₕ∙_ {n = n}) helper = makeIsGroup § (assocₕ∙ n) (rUnitₕ∙ n) (lUnitₕ∙ n) (rCancelₕ∙ n) (lCancelₕ∙ n) IsAbGroup.comm (AbGroupStr.isAbGroup (snd (coHomRedGroupDir n A))) = commₕ∙ n coHomRedGrDir : (n : ℕ) (A : Pointed ℓ) → Group {ℓ} coHomRedGrDir n A = AbGroup→Group (coHomRedGroupDir n A) -- Induced map coHomFun : ∀ {ℓ ℓ'} {A : Type ℓ} {B : Type ℓ'} (n : ℕ) (f : A → B) → coHom n B → coHom n A coHomFun n f = sRec § λ β → ∣ β ∘ f ∣₂ coHomMorph : ∀ {ℓ ℓ'} {A : Type ℓ} {B : Type ℓ'} (n : ℕ) (f : A → B) → GroupHom (coHomGr n B) (coHomGr n A) fun (coHomMorph n f) = coHomFun n f isHom (coHomMorph zero f) = sElim2 (λ _ _ → isOfHLevelPath 2 § _ _) λ _ _ → refl isHom (coHomMorph (suc zero) f) = sElim2 (λ _ _ → isOfHLevelPath 2 § _ _) λ _ _ → refl isHom (coHomMorph (suc (suc n)) f) = sElim2 (λ _ _ → isOfHLevelPath 2 § _ _) λ _ _ → refl -- Alternative definition of cohomology using ΩKₙ instead. Useful for breaking proofs of group isos -- up into smaller parts coHomGrΩ : ∀ {ℓ} (n : ℕ) (A : Type ℓ) → Group {ℓ} coHomGrΩ n A = ∥ (A → typ (Ω (coHomK-ptd (suc n)))) ∥₂ , coHomGrnA where coHomGrnA : GroupStr ∥ (A → typ (Ω (coHomK-ptd (suc n)))) ∥₂ 0g coHomGrnA = ∣ (λ _ → refl) ∣₂ GroupStr._+_ coHomGrnA = sRec2 § λ p q → ∣ (λ x → p x ∙ q x) ∣₂ - coHomGrnA = map λ f x → sym (f x) isGroup coHomGrnA = helper where abstract helper : IsGroup {G = ∥ (A → typ (Ω (coHomK-ptd (suc n)))) ∥₂} (∣ (λ _ → refl) ∣₂) (sRec2 § λ p q → ∣ (λ x → p x ∙ q x) ∣₂) (map λ f x → sym (f x)) helper = makeIsGroup § (elim3 (λ _ _ _ → isOfHLevelPath 2 § _ _) (λ p q r → cong ∣_∣₂ (funExt λ x → assoc∙ (p x) (q x) (r x)))) (sElim (λ _ → isOfHLevelPath 2 § _ _) λ p → cong ∣_∣₂ (funExt λ x → sym (rUnit (p x)))) (sElim (λ _ → isOfHLevelPath 2 § _ _) λ p → cong ∣_∣₂ (funExt λ x → sym (lUnit (p x)))) (sElim (λ _ → isOfHLevelPath 2 § _ _) λ p → cong ∣_∣₂ (funExt λ x → rCancel (p x))) (sElim (λ _ → isOfHLevelPath 2 § _ _) λ p → cong ∣_∣₂ (funExt λ x → lCancel (p x))) --- the loopspace of Kₙ is commutative regardless of base addIso : (n : ℕ) (x : coHomK n) → Iso (coHomK n) (coHomK n) fun (addIso n x) y = y +[ n ]ₖ x inv' (addIso n x) y = y -[ n ]ₖ x rightInv (addIso n x) y = -+cancelₖ n y x leftInv (addIso n x) y = -cancelRₖ n x y isCommΩK-based : (n : ℕ) (x : coHomK n) → isComm∙ (coHomK n , x) isCommΩK-based zero x p q = isSetInt _ _ (p ∙ q) (q ∙ p) isCommΩK-based (suc zero) x = subst isComm∙ (λ i → coHomK 1 , lUnitₖ 1 x i) (ptdIso→comm {A = (_ , 0ₖ 1)} (addIso 1 x) (isCommΩK 1)) isCommΩK-based (suc (suc n)) x = subst isComm∙ (λ i → coHomK (suc (suc n)) , lUnitₖ (suc (suc n)) x i) (ptdIso→comm {A = (_ , 0ₖ (suc (suc n)))} (addIso (suc (suc n)) x) (isCommΩK (suc (suc n)))) -- hidden versions of cohom stuff using the ""lock"" hack. The locked versions can be used when proving things. -- Swapping ""key"" for ""tt*"" will then give computing functions. Unit' : Type₀ Unit' = lockUnit {ℓ-zero} lock : ∀ {ℓ} {A : Type ℓ} → Unit' → A → A lock unlock = λ x → x module lockedCohom (key : Unit') where +K : (n : ℕ) → coHomK n → coHomK n → coHomK n +K n = lock key (_+ₖ_ {n = n}) -K : (n : ℕ) → coHomK n → coHomK n -K n = lock key (-ₖ_ {n = n}) -Kbin : (n : ℕ) → coHomK n → coHomK n → coHomK n -Kbin n x y = +K n x (-K n y) rUnitK : (n : ℕ) (x : coHomK n) → +K n x (0ₖ n) ≡ x rUnitK n x = pm key where pm : (t : Unit') → lock t (_+ₖ_ {n = n}) x (0ₖ n) ≡ x pm unlock = rUnitₖ n x lUnitK : (n : ℕ) (x : coHomK n) → +K n (0ₖ n) x ≡ x lUnitK n x = pm key where pm : (t : Unit') → lock t (_+ₖ_ {n = n}) (0ₖ n) x ≡ x pm unlock = lUnitₖ n x rCancelK : (n : ℕ) (x : coHomK n) → +K n x (-K n x) ≡ 0ₖ n rCancelK n x = pm key where pm : (t : Unit') → lock t (_+ₖ_ {n = n}) x (lock t (-ₖ_ {n = n}) x) ≡ 0ₖ n pm unlock = rCancelₖ n x lCancelK : (n : ℕ) (x : coHomK n) → +K n (-K n x) x ≡ 0ₖ n lCancelK n x = pm key where pm : (t : Unit') → lock t (_+ₖ_ {n = n}) (lock t (-ₖ_ {n = n}) x) x ≡ 0ₖ n pm unlock = lCancelₖ n x -cancelRK : (n : ℕ) (x y : coHomK n) → -Kbin n (+K n y x) x ≡ y -cancelRK n x y = pm key where pm : (t : Unit') → lock t (_+ₖ_ {n = n}) (lock t (_+ₖ_ {n = n}) y x) (lock t (-ₖ_ {n = n}) x) ≡ y pm unlock = -cancelRₖ n x y -cancelLK : (n : ℕ) (x y : coHomK n) → -Kbin n (+K n x y) x ≡ y -cancelLK n x y = pm key where pm : (t : Unit') → lock t (_+ₖ_ {n = n}) (lock t (_+ₖ_ {n = n}) x y) (lock t (-ₖ_ {n = n}) x) ≡ y pm unlock = -cancelLₖ n x y -+cancelK : (n : ℕ) (x y : coHomK n) → +K n (-Kbin n x y) y ≡ x -+cancelK n x y = pm key where pm : (t : Unit') → lock t (_+ₖ_ {n = n}) (lock t (_+ₖ_ {n = n}) x (lock t (-ₖ_ {n = n}) y)) y ≡ x pm unlock = -+cancelₖ n x y assocK : (n : ℕ) (x y z : coHomK n) → +K n x (+K n y z) ≡ +K n (+K n x y) z assocK n x y z = pm key where pm : (t : Unit') → lock t (_+ₖ_ {n = n}) x (lock t (_+ₖ_ {n = n}) y z) ≡ lock t (_+ₖ_ {n = n}) (lock t (_+ₖ_ {n = n}) x y) z pm unlock = assocₖ n x y z commK : (n : ℕ) (x y : coHomK n) → +K n x y ≡ +K n y x commK n x y = pm key where pm : (t : Unit') → lock t (_+ₖ_ {n = n}) x y ≡ lock t (_+ₖ_ {n = n}) y x pm unlock = commₖ n x y -- cohom +H : (n : ℕ) (x y : coHom n A) → coHom n A +H n = sRec2 § λ a b → ∣ (λ x → +K n (a x) (b x)) ∣₂ -H : (n : ℕ) (x : coHom n A) → coHom n A -H n = sRec § λ a → ∣ (λ x → -K n (a x)) ∣₂ -Hbin : (n : ℕ) → coHom n A → coHom n A → coHom n A -Hbin n = sRec2 § λ a b → ∣ (λ x → -Kbin n (a x) (b x)) ∣₂ rUnitH : (n : ℕ) (x : coHom n A) → +H n x (0ₕ n) ≡ x rUnitH n = sElim (λ _ → isOfHLevelPath 1 (§ _ _)) λ a i → ∣ funExt (λ x → rUnitK n (a x)) i ∣₂ lUnitH : (n : ℕ) (x : coHom n A) → +H n (0ₕ n) x ≡ x lUnitH n = sElim (λ _ → isOfHLevelPath 1 (§ _ _)) λ a i → ∣ funExt (λ x → lUnitK n (a x)) i ∣₂ rCancelH : (n : ℕ) (x : coHom n A) → +H n x (-H n x) ≡ 0ₕ n rCancelH n = sElim (λ _ → isOfHLevelPath 1 (§ _ _)) λ a i → ∣ funExt (λ x → rCancelK n (a x)) i ∣₂ lCancelH : (n : ℕ) (x : coHom n A) → +H n (-H n x) x ≡ 0ₕ n lCancelH n = sElim (λ _ → isOfHLevelPath 1 (§ _ _)) λ a i → ∣ funExt (λ x → lCancelK n (a x)) i ∣₂ assocH : (n : ℕ) (x y z : coHom n A) → (+H n x (+H n y z)) ≡ (+H n (+H n x y) z) assocH n = elim3 (λ _ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b c i → ∣ funExt (λ x → assocK n (a x) (b x) (c x)) i ∣₂ commH : (n : ℕ) (x y : coHom n A) → (+H n x y) ≡ (+H n y x) commH n = sElim2 (λ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b i → ∣ funExt (λ x → commK n (a x) (b x)) i ∣₂ -cancelRH : (n : ℕ) (x y : coHom n A) → -Hbin n (+H n y x) x ≡ y -cancelRH n = sElim2 (λ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b i → ∣ (λ x → -cancelRK n (a x) (b x) i) ∣₂ -cancelLH : (n : ℕ) (x y : coHom n A) → -Hbin n (+H n x y) x ≡ y -cancelLH n = sElim2 (λ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b i → ∣ (λ x → -cancelLK n (a x) (b x) i) ∣₂ -+cancelH : (n : ℕ) (x y : coHom n A) → +H n (-Hbin n x y) y ≡ x -+cancelH n = sElim2 (λ _ _ → isOfHLevelPath 1 (§ _ _)) λ a b i → ∣ (λ x → -+cancelK n (a x) (b x) i) ∣₂ lUnitK≡rUnitK : (key : Unit') (n : ℕ) → lockedCohom.lUnitK key n (0ₖ n) ≡ lockedCohom.rUnitK key n (0ₖ n) lUnitK≡rUnitK unlock = lUnitₖ≡rUnitₖ open GroupIso renaming (map to grMap) open GroupStr renaming (_+_ to _+gr_) open GroupHom inducedCoHom : ∀ {ℓ ℓ'} {A : Type ℓ} {G : Group {ℓ'}} {n : ℕ} → GroupIso (coHomGr n A) G → Group inducedCoHom {A = A} {G = G} {n = n} e = InducedGroup (coHomGr n A) (coHom n A , λ x y → inv e (_+gr_ (snd G) (fun (grMap e) x) (fun (grMap e) y))) (idEquiv _) λ x y → sym (leftInv e _) ∙ cong (inv e) (isHom (grMap e) x y) induced+ : ∀ {ℓ ℓ'} {A : Type ℓ} {G : Group {ℓ'}} {n : ℕ} → (e : GroupIso (coHomGr n A) G) → fst (inducedCoHom e) → fst (inducedCoHom e) → fst (inducedCoHom e) induced+ e = _+gr_ (snd (inducedCoHom e)) inducedCoHomIso : ∀ {ℓ ℓ'} {A : Type ℓ} {G : Group {ℓ'}} {n : ℕ} → (e : GroupIso (coHomGr n A) G) → GroupIso (coHomGr n A) (inducedCoHom e) fun (grMap (inducedCoHomIso e)) = idfun _ isHom (grMap (inducedCoHomIso e)) x y = sym (leftInv e _) ∙ cong (inv e) (isHom (grMap e) x y) inv (inducedCoHomIso e) = idfun _ rightInv (inducedCoHomIso e) _ = refl leftInv (inducedCoHomIso e) _ = refl inducedCoHomPath : ∀ {ℓ ℓ'} {A : Type ℓ} {G : Group {ℓ'}} {n : ℕ} → (e : GroupIso (coHomGr n A) G) → coHomGr n A ≡ inducedCoHom e inducedCoHomPath e = InducedGroupPath _ _ _ _ ",16226,True,3501.4083078750564,median "module BTA9 where ---------------------------------------------- -- Preliminaries: Imports and List-utilities ---------------------------------------------- open import Data.Nat hiding (_<_;_⊔_;_*_;equal) open import Data.Bool hiding (_∧_;_∨_) open import Function using (_∘_) open import Data.List open import Data.Nat.Properties open import Relation.Nullary open import Relation.Binary.PropositionalEquality open import Data.Empty open import Lib --------------------------------------- -- Start of the development: --------------------------------------- -- Intro/Objective: ------------------- -- The following development defines a (verified) specializer/partial -- evaluator for a simply typed lambda calculus embedded in Agda using -- deBruijn indices. -- The residual language. ------------------------- -- The residual language is a standard simply typed λ-calculus. The -- types are integers,functions,pairs,and sums. data Type : Set where Int : Type Fun : Type → Type → Type --pair type on the residual type level _•_ : Type → Type → Type --sum type on the residual type level _⊎_ : Type → Type → Type Ctx = List Type -- The type Exp describes the typed residual expressions. Variables -- are represented by deBruijn indices that form references into the -- typing context. The constructors and typing constraints are -- standard. -- TODO: citations for ``as usual'' and ``standard'' -- what? data Exp (Γ : Ctx) : Type → Set where EVar : ∀ {τ} → τ ∈ Γ → Exp Γ τ EInt : ℕ → Exp Γ Int EAdd : Exp Γ Int → Exp Γ Int -> Exp Γ Int ELam : ∀ {τ τ'} → Exp (τ ∷ Γ) τ' → Exp Γ (Fun τ τ') EApp : ∀ {τ τ'} → Exp Γ (Fun τ τ') → Exp Γ τ → Exp Γ τ' _,_ : ∀ {τ τ'} → Exp Γ τ → Exp Γ τ' → Exp Γ (τ • τ') Tl : ∀ {τ τ'} → Exp Γ τ → Exp Γ (τ ⊎ τ') Tr : ∀ {τ τ'} → Exp Γ τ' → Exp Γ (τ ⊎ τ') EFst : ∀ {τ τ'} → Exp Γ (τ • τ') → Exp Γ τ ESnd : ∀ {τ τ'} → Exp Γ (τ • τ') → Exp Γ τ' ECase : ∀ {τ τ' τ''} → Exp Γ (τ ⊎ τ') → Exp (τ ∷ Γ) τ'' → Exp (τ' ∷ Γ) τ'' → Exp Γ τ'' -- The standard functional semantics of the residual expressions. -- TODO: citations for ``as usual'' and ``standard'' -- what? module Exp-Eval where -- interpretation of Exp types EImp : Type → Set EImp Int = ℕ EImp (Fun ty ty₁) = EImp ty → EImp ty₁ EImp (ty • ty₁) = EImp ty * EImp ty₁ EImp (ty ⊎ ty₁) = EImp ty ⨄ EImp ty₁ -- Environments containing values for free variables. An environment -- is indexed by a typing context that provides the types for the -- contained values. data Env : Ctx → Set where [] : Env [] _∷_ : ∀ {τ Γ} → EImp τ → Env Γ → Env (τ ∷ Γ) -- Lookup a value in the environment, given a reference into the -- associated typing context. lookupE : ∀ { τ Γ } → τ ∈ Γ → Env Γ → EImp τ lookupE hd (x ∷ env) = x lookupE (tl v) (x ∷ env) = lookupE v env -- Evaluation of residual terms, given a suitably typed environment. ev : ∀ {τ Γ} → Exp Γ τ → Env Γ → EImp τ ev (EVar x) env = lookupE x env ev (EInt x) env = x ev (EAdd e e₁) env = ev e env + ev e₁ env ev (ELam e) env = λ x → ev e (x ∷ env) ev (EApp e e₁) env = ev e env (ev e₁ env) ev (e , e₁) env = ev e env , (ev e₁ env) ev (Tl e) env = tl (ev e env) ev (Tr e) env = tr (ev e env) ev (EFst e) env = fst (ev e env) ev (ESnd e) env = snd (ev e env) ev (ECase e e₁ e₂) env with ev e env ev (ECase e e₁ e₂) env | tl c = (λ x → ev e₁ (x ∷ env)) c ev (ECase e e₁ e₂) env | tr c = (λ x → ev e₂ (x ∷ env)) c -- The binding-time-annotated language. --------------------------------------- -- The type of a term determines the term's binding time. The type -- constructors with an A-prefix denote statically bound integers and -- functions. Terms with dynamic binding time have a `D' type. The `D' -- type constructor simply wraps up a residual type. data AType : Set where AInt : AType AFun : AType → AType → AType D : Type → AType --pair type on the annotated type level _•_ : AType → AType → AType --sum type on the annotated type level _⊎_ : AType → AType → AType ACtx = List AType -- The mapping from annotated types to residual types is straightforward. typeof : AType → Type typeof AInt = Int typeof (AFun α₁ α₂) = Fun (typeof α₁) (typeof α₂) typeof (D x) = x typeof (α₁ • α₂) = typeof α₁ • typeof α₂ typeof (α₁ ⊎ α₂) = typeof α₁ ⊎ typeof α₂ -- The typed annotated terms: The binding times of variables is -- determined by the corresponding type-binding in the context. In the -- other cases, the A- and D-prefixes on term constructors inidicate -- the corresponding binding times for the resulting terms. ------------------------------------------------------------------------------------------------ -- Now the typed annotated terms are extended to inculde dynamic terms whose subterms are static ------------------------------------------------------------------------------------------------ --------------- --Some examples --------------- --a. first-order static value in a dynamic environment -- DAdd (DInt 1) (AAdd (AInt 2) (AInt 3)) where AAdd (AInt 2) (AInt 3) : AExp [] AInt -- DAdd (DInt 1) (AApp (ALam (Var hd)) (AInt 5)) where AApp (ALam (Var hd)) (AInt 5) : AExp [] AInt --b. higher-order static value in a dynamic environment -- DApp (ALam (Var hd)) (DInt 5) where ALam (Var hd) : AExp [] (AFun (D Int) (D Int)) -- DApp (ALam (ALam (AInt 0))) (DInt 5) where ALam (ALam (AInt 0)) : AExp [] (AFun (AFun (D Int) (D Int)) AInt) -- DApp (ALam (ALam (DInt 0))) (DInt 5) where ALam (ALam (DInt 0)) : AExp [] (AFun (AFun AInt (D Int)) (D Int)) --Clearly these terms are not well-typed and we need to modify [AExp] such that they have the right types which are --compatible with the dynamic environment,or we can ""lift"" their static types to dynamic types so that they can be --used as dynamic sub-terms to be filled in the right dynamic environment. This,however,brings new difficulty when --we try to partially evaluate term who contains ""lifted"" subterms. ---------------- --new difficulty ---------------- --Consider the evaluation of the following term --DAdd (DInt 1) (Lift (AAdd (AInt 2) (AInt 3))) : AExp [] AInt --the expected type after evaluation is, --EAdd (EInt 1) ? : Exp [] Int where ? : Exp [] Int --and one good candidate for ""?"" as, --EInt (pe (AAdd (AInt 2) (AInt 3)) []) : Exp [] Int --where we wrap up the partial evaluation of the static subterm so --that it fits with the rest of evaluation. --However,we can not always ""wrap up"" a evaluated higher-order static --value so that it has the required residual type, --ALam (Var hd) : AExp [] (AFun AInt AInt) --the required type of its lifted term as, --? : Exp [] (Fun Int Int) --which can not be constructed from [λ Γ↝Γ' x → x : []↝Γ' → ℕ → ℕ] --for the input of the static function is evaluated to be a natural --number which can not be matched with the type of the input of the --required residual term. It is then clear that we need to impose --restriction upon terms to be lifted. ------------------------- --restriction for lifting ------------------------- ------------------------------------------------------------- -- The interpretation of annotated types. Imp : Ctx → AType → Set Imp Γ (AInt) = ℕ Imp Γ (AFun α₁ α₂) = ∀ {Γ'} → Γ ↝ Γ' → (Imp Γ' α₁ → Imp Γ' α₂) Imp Γ (D σ) = Exp Γ σ Imp Γ (α₁ • α₂) = (Imp Γ α₁) * (Imp Γ α₂) Imp Γ (α₁ ⊎ α₂) = (Imp Γ α₁) ⨄ (Imp Γ α₂) elevate-var : ∀ {Γ Γ'} {τ : Type} → Γ ↝ Γ' → τ ∈ Γ → τ ∈ Γ' elevate-var ↝-refl x = x elevate-var (↝-extend Γ↝Γ') x = tl (elevate-var Γ↝Γ' x) elevate-var2 : ∀ {Γ Γ' Γ'' τ} → Γ ↝ Γ' ↝ Γ'' → τ ∈ Γ → τ ∈ Γ'' elevate-var2 (↝↝-base x) x₁ = elevate-var x x₁ elevate-var2 (↝↝-extend Γ↝Γ'↝Γ'') hd = hd elevate-var2 (↝↝-extend Γ↝Γ'↝Γ'') (tl x) = tl (elevate-var2 Γ↝Γ'↝Γ'' x) elevate : ∀ {Γ Γ' Γ'' τ} → Γ ↝ Γ' ↝ Γ'' → Exp Γ τ → Exp Γ'' τ elevate Γ↝Γ'↝Γ'' (EVar x) = EVar (elevate-var2 Γ↝Γ'↝Γ'' x) elevate Γ↝Γ'↝Γ'' (EInt x) = EInt x elevate Γ↝Γ'↝Γ'' (EAdd e e₁) = EAdd (elevate Γ↝Γ'↝Γ'' e) (elevate Γ↝Γ'↝Γ'' e₁) elevate Γ↝Γ'↝Γ'' (ELam e) = ELam (elevate (↝↝-extend Γ↝Γ'↝Γ'') e) elevate Γ↝Γ'↝Γ'' (EApp e e₁) = EApp (elevate Γ↝Γ'↝Γ'' e) (elevate Γ↝Γ'↝Γ'' e₁) elevate Γ↝Γ'↝Γ'' (e , e₁) = ((elevate Γ↝Γ'↝Γ'' e) , (elevate Γ↝Γ'↝Γ'' e₁)) elevate Γ↝Γ'↝Γ'' (Tl e) = Tl (elevate Γ↝Γ'↝Γ'' e) elevate Γ↝Γ'↝Γ'' (Tr e) = Tr (elevate Γ↝Γ'↝Γ'' e) elevate Γ↝Γ'↝Γ'' (EFst e) = EFst (elevate Γ↝Γ'↝Γ'' e) elevate Γ↝Γ'↝Γ'' (ESnd e) = ESnd (elevate Γ↝Γ'↝Γ'' e) elevate Γ↝Γ'↝Γ'' (ECase c e₁ e₂) = ECase (elevate Γ↝Γ'↝Γ'' c) (elevate (↝↝-extend Γ↝Γ'↝Γ'') e₁) (elevate (↝↝-extend Γ↝Γ'↝Γ'') e₂) liftE : ∀ {τ Γ Γ'} → Γ ↝ Γ' → Exp Γ τ → Exp Γ' τ liftE Γ↝Γ' e = elevate (↝↝-base Γ↝Γ') e ------------------------------------------------------------- -- --case 1. a first-order static value in a dynamic environment -- lift1 : AExp [] AInt -- lift1 = (AInt 0) -- e1 : Imp [] AInt -- e1 = 0 -- lifted1 : Exp [] (typeof AInt) -- lifted1 = EInt e1 -- --case 2. higher-order static function in a dynamic environment -- --a. a function whose input argument is of static integer -- --lift2 : AExp [] (AFun AInt AInt) -- --lift2 = ALam (Var hd) -- --e2 : Imp [] (AFun AInt AInt) -- --e2 = λ Γ↝Γ' x → x -- --lifted2 : Exp [] (typeof (AFun AInt AInt)) -- --lifted2 = ELam {!!} -- --Note that as explained above it is impossible to construct the right term using [e2] -- --to fill in the above hole! -- --b. a function whose input argument is of dynamic integer -- --b.1. when return type is of dynamic integer -- lift3 : AExp [] (AFun (D Int) (D Int)) -- lift3 = ALam (Var hd) -- e3 : Imp [] (AFun (D Int) (D Int)) -- e3 = λ Γ↝Γ' x → x -- liftede3 : Exp [] (typeof (AFun (D Int) (D Int))) -- liftede3 = ELam (e3 (↝-extend ↝-refl) (EVar hd)) -- --b.2. when return type is of static integer -- lift4 : AExp [] (AFun (D Int) AInt) -- lift4 = ALam (AInt 0) -- e4 : Imp [] (AFun (D Int) AInt) -- e4 = λ Γ↝Γ' x → 0 -- liftede4 : Exp [] (typeof (AFun (D Int) AInt)) -- liftede4 = ELam ( EInt {Int ∷ []} (e4 (↝-extend ↝-refl) (EVar hd))) -- --c. a function whose input argument is of static function type -- --c.1. static function type returns a static integer -- --lift5 : AExp [] (AFun (AFun AInt AInt) AInt) -- --lift5 = ALam (AApp (Var hd) (AInt 0)) -- --e5 : Imp [] (AFun (AFun AInt AInt) AInt) -- --e5 = λ Γ↝Γ' x → x ↝-refl 0 -- --liftede5 : Exp [] (typeof ( AFun (AFun AInt AInt) AInt)) -- --liftede5 = ELam (EInt (e5 (↝-extend {τ = Fun Int Int} ↝-refl) (λ Γ↝Γ' e' → {!!}))) -- --Note that again it is impossible to construct the right residual term -- --c.2. static function type returns a dynamic integer -- --c.2.1. the input of the function type is of static integer -- lift6 : AExp [] (AFun (AFun AInt (D Int)) (D Int)) -- lift6 = ALam (AApp (Var hd) (AInt 0)) -- e6 : Imp [] (AFun (AFun AInt (D Int)) (D Int)) -- e6 = λ Γ↝Γ' x → x ↝-refl 0 -- liftede6 : Exp [] (typeof ( AFun (AFun AInt (D Int)) (D Int))) -- liftede6 = ELam ((e6 (↝-extend {τ = Fun Int Int} ↝-refl) -- (λ Γ↝Γ' e' → EApp (liftE Γ↝Γ' (EVar {Fun Int Int ∷ []} hd)) (EInt e')))) -- --c.2.1. the input of the function type is of dynamic integer -- lift7 : AExp [] (AFun (AFun (D Int) (D Int)) (D Int)) -- lift7 = ALam (AApp (Var hd) (DInt 0)) -- e7 : Imp [] (AFun (AFun (D Int) (D Int)) (D Int)) -- e7 = λ Γ↝Γ' x → x ↝-refl (EInt 0) -- liftede7 : Exp [] (typeof ( AFun (AFun (D Int) (D Int)) (D Int))) -- liftede7 = ELam ((e7 (↝-extend {τ = Fun Int Int} ↝-refl) -- (λ Γ↝Γ' e' → EApp (liftE Γ↝Γ' (EVar {Fun Int Int ∷ []} hd)) e'))) -- --c.3. the output of the function type is of higher-order static value -- --c.3.1 the return value has one static integer as input -- -- lift8 : AExp [] (AFun (D Int) (AFun AInt (D Int))) -- -- lift8 = ALam (ALam (Var (tl hd))) -- -- e8 : Imp [] (AFun (D Int) (AFun AInt (D Int))) -- -- e8 = λ Γ↝Γ' x Γ'↝Γ'' y → liftE Γ'↝Γ'' x -- -- liftede8 : Exp [] (typeof ( AFun (D Int) (AFun AInt (D Int)))) -- -- liftede8 = ELam (ELam (e8 (↝-extend (↝-extend ↝-refl)) (EVar (tl hd)) ↝-refl {!!})) -- --c.3.2 the return value has one dynamic integer as input -- lift9 : AExp [] (AFun (D Int) (AFun (D Int) (D Int))) -- lift9 = ALam (ALam (Var (tl hd))) -- e9 : Imp [] (AFun (D Int) (AFun (D Int) (D Int))) -- e9 = λ Γ↝Γ' x Γ'↝Γ'' y → liftE Γ'↝Γ'' x -- liftede9 : Exp [] (typeof ( AFun (D Int) (AFun (D Int) (D Int)))) -- liftede9 = ELam (ELam (e9 (↝-extend (↝-extend ↝-refl)) (EVar (tl hd)) ↝-refl (EVar hd))) -- --d. static pairs and sums in dynamic environment -- --d.1. identity function with static sum as its input -- lift10 : AExp [] (AFun ((D Int) ⊎ (D Int)) ((D Int) ⊎ (D Int))) -- lift10 = ALam (Var hd) -- e10 : Imp [] (AFun ((D Int) ⊎ (D Int)) ((D Int) ⊎ (D Int))) -- e10 = λ Γ↝Γ' x → x -- liftede10 : Exp [] (typeof (AFun ((D Int) ⊎ (D Int)) ((D Int) ⊎ (D Int)))) -- liftede10 = ELam {!e10!} -- --d.1. identity function with static sum as its input -- lift11 : AExp [] (AFun ((D Int) • (D Int)) ((D Int) • (D Int))) -- lift11 = ALam (Var hd) -- e11 : Imp [] (AFun ((D Int) • (D Int)) ((D Int) • (D Int))) -- e11 = λ Γ↝Γ' x → x -- liftede11 : Exp [] (typeof (AFun ((D Int) • (D Int)) ((D Int) • (D Int)))) -- liftede11 = ELam (fst (e11 (↝-extend ↝-refl) (EFst (EVar hd) , ESnd (EVar hd))) , -- snd (e11 (↝-extend ↝-refl) (EFst (EVar hd) , ESnd (EVar hd)))) --Note that the above two examples in section ""d"" clearly shows that --""static functions with inputs of static sum type are not liftable -- while with inputs of static pair type are liftable "". --------------------------- --summary on liftable terms --------------------------- --a. Regarding static first-order static value (static integer) in dynamic environment -- All terms of static integer type are liftable --b. Regarding static higher-order static value in dynamic environment --b.1. given that output value is liftable -- • when input is of first-order dynamic type,liftable -- • when input is of higher-order static type and output -- of that input is of dynamic type,liftable --b.2. given that input value is liftable -- • when output is of first-order type,liftable -- • when output is of higher-order type and inputs -- of that type are of dynamic type,liftable ------------------------------------------- --specification of the liftable restriction ------------------------------------------- mutual data Liftable : AType → Set where D : ∀ τ → Liftable (D τ) AInt : Liftable AInt _⊎_ : ∀ {α₁ α₂} → Liftable α₁ → Liftable α₂ → Liftable (α₁ ⊎ α₂) _•_ : ∀ {α₁ α₂} → Liftable α₁ → Liftable α₂ → Liftable (α₁ • α₂) AFun : ∀ {α₁ α₂} → Liftable⁻ α₁ → Liftable α₂ → Liftable (AFun α₁ α₂) data Liftable⁻ : AType → Set where D : ∀ τ → Liftable⁻ (D τ) _•_ : ∀ {α₁ α₂} → Liftable⁻ α₁ → Liftable⁻ α₂ → Liftable⁻ (α₁ • α₂) AFun : ∀ {α₁ α₂} → Liftable α₁ → Liftable⁻ α₂ → Liftable⁻ (AFun α₁ α₂) ---------------------------------------- --[AExp] with liftable terms ---------------------------------------- data AExp (Δ : ACtx) : AType → Set where Var : ∀ {α} → α ∈ Δ → AExp Δ α AInt : ℕ → AExp Δ AInt AAdd : AExp Δ AInt → AExp Δ AInt → AExp Δ AInt ALam : ∀ {α₁ α₂} → AExp (α₁ ∷ Δ) α₂ → AExp Δ (AFun α₁ α₂) AApp : ∀ {α₁ α₂} → AExp Δ (AFun α₂ α₁) → AExp Δ α₂ → AExp Δ α₁ DInt : ℕ → AExp Δ (D Int) DAdd : AExp Δ (D Int) → AExp Δ (D Int) → AExp Δ (D Int) DLam : ∀ {σ₁ σ₂} → AExp ((D σ₁) ∷ Δ) (D σ₂) → AExp Δ (D (Fun σ₁ σ₂)) DApp : ∀ {α₁ α₂} → AExp Δ (D (Fun α₂ α₁)) → AExp Δ (D α₂) → AExp Δ (D α₁) -- Static pairs and sums _,_ : ∀ {α₁ α₂} → AExp Δ α₁ → AExp Δ α₂ → AExp Δ (α₁ • α₂) Tl : ∀ {α₁ α₂} → AExp Δ α₁ → AExp Δ (α₁ ⊎ α₂) Tr : ∀ {α₁ α₂} → AExp Δ α₂ → AExp Δ (α₁ ⊎ α₂) Fst : ∀ {α₁ α₂} → AExp Δ (α₁ • α₂) → AExp Δ α₁ Snd : ∀ {α₁ α₂} → AExp Δ (α₁ • α₂) → AExp Δ α₂ Case : ∀ {α₁ α₂ α₃} → AExp Δ (α₁ ⊎ α₂) → AExp (α₁ ∷ Δ) α₃ → AExp (α₂ ∷ Δ) α₃ → AExp Δ α₃ -- Dynamic pairs and sums _ḋ_ : ∀ {σ₁ σ₂} → AExp Δ (D σ₁) → AExp Δ (D σ₂) → AExp Δ (D (σ₁ • σ₂)) DTl : ∀ {σ₁ σ₂} → AExp Δ (D σ₁) → AExp Δ (D (σ₁ ⊎ σ₂)) DTr : ∀ {σ₁ σ₂} → AExp Δ (D σ₂) → AExp Δ (D (σ₁ ⊎ σ₂)) DFst : ∀ {σ₁ σ₂} → AExp Δ (D (σ₁ • σ₂)) → AExp Δ (D σ₁) DSnd : ∀ {σ₁ σ₂} → AExp Δ (D (σ₁ • σ₂)) → AExp Δ (D σ₂) DCase : ∀ {σ₁ σ₂ σ₃} → AExp Δ (D (σ₁ ⊎ σ₂)) → AExp ((D σ₁) ∷ Δ) (D σ₃) → AExp ((D σ₂) ∷ Δ) (D σ₃) → AExp Δ (D σ₃) -- Liftable static terms ↑ : ∀ {α} → Liftable α → AExp Δ α → AExp Δ (D (typeof α)) -- The terms of AExp assign a binding time to each subterm. For -- program specialization, we interpret terms with dynamic binding -- time as the programs subject to specialization, and their subterms -- with static binding time as statically known inputs. A partial -- evaluation function (or specializer) then compiles the program into -- a residual term for that is specialized for the static inputs. The -- main complication when defining partial evaluation as a total, -- primitively recursive function will be the treatment of the De -- Bruijn variables of non-closed residual expressions. lift : ∀ {Γ Γ'} α → Γ ↝ Γ' → Imp Γ α → Imp Γ' α lift AInt p v = v lift (AFun x x₁) Γ↝Γ' v = λ Γ'↝Γ'' → v (↝-trans Γ↝Γ' Γ'↝Γ'') lift (D x₁) Γ↝Γ' v = elevate (↝↝-base Γ↝Γ') v lift (α₁ • α₂) Γ↝Γ' (v₁ , v₂) = (lift α₁ Γ↝Γ' v₁) , (lift α₂ Γ↝Γ' v₂) lift (α₁ ⊎ α₂) Γ↝Γ' (tl v) = tl (lift α₁ Γ↝Γ' v) lift (α₁ ⊎ α₂) Γ↝Γ' (tr v) = tr (lift α₂ Γ↝Γ' v) module SimpleAEnv where -- A little weaker, but much simpler data AEnv (Γ : Ctx) : ACtx → Set where [] : AEnv Γ [] --cons : ∀ {Δ} (α : AType) → Imp Γ α → AEnv Γ Δ → AEnv Γ (α ∷ Δ) cons : ∀ {Δ} {α : AType} → Imp Γ α → AEnv Γ Δ → AEnv Γ (α ∷ Δ) lookup : ∀ {α Δ Γ} → AEnv Γ Δ → α ∈ Δ → Imp Γ α lookup [] () --lookup {α} (cons .α x aenv) hd = x --lookup {α} (cons .y x aenv) (tl {.α} {y} id) = lookup aenv id lookup {α} (cons x aenv) hd = x lookup {α} (cons x aenv) (tl {.α} {y} id) = lookup aenv id liftEnv : ∀ {Γ Γ' Δ} → Γ ↝ Γ' → AEnv Γ Δ → AEnv Γ' Δ liftEnv Γ↝Γ' [] = [] --liftEnv Γ↝Γ' (cons α x env) = cons α (lift α Γ↝Γ' x) (liftEnv Γ↝Γ' env) liftEnv Γ↝Γ' (cons {α = α} x env) = cons {α = α} (lift α Γ↝Γ' x) (liftEnv Γ↝Γ' env) consD : ∀ {Γ Δ} σ → AEnv Γ Δ → AEnv (σ ∷ Γ) (D σ ∷ Δ) --consD σ env = (cons (D σ) (EVar hd) (liftEnv (↝-extend {τ = σ} ↝-refl) env)) consD σ env = (cons {α = D σ} (EVar hd) (liftEnv (↝-extend {τ = σ} ↝-refl) env)) ---------------------------------------------- -- Helper for the evaluation of liftable terms ---------------------------------------------- mutual lift' : ∀ {Γ α} → Liftable α → Imp Γ α → (Exp Γ (typeof α)) lift' (D τ) v = v lift' AInt v = EInt v lift' (ty ⊎ ty₁) (tl a) = Tl (lift' ty a) lift' (ty ⊎ ty₁) (tr b) = Tr (lift' ty₁ b) lift' (ty • ty₁) (ffst , ssnd) = lift' ty ffst , lift' ty₁ ssnd lift' {Γ} (AFun {α₁} ty₁ ty₂) v = ELam ((λ x → lift' ty₂ (v (↝-extend {τ = typeof α₁} ↝-refl) x)) (embed ty₁ (EVar {Γ = typeof α₁ ∷ Γ} hd))) embed : ∀ {Γ α} → Liftable⁻ α → Exp Γ (typeof α) → (Imp Γ α) embed (D τ) e = e -- embed (ty ⊎ ty₁) e = {! (ECase e (EVar hd) ?)!} -- embed (ty ⊎ ty₁) (EVar x) = {!!} -- embed (ty ⊎ ty₁) (EApp e e₁) = {!!} -- embed (ty ⊎ ty₁) (Tl e) = tl (embed ty e) -- embed (ty ⊎ ty₁) (Tr e) = tr (embed ty₁ e) -- embed (ty ⊎ ty₁) (EFst e) = {!!} -- embed (ty ⊎ ty₁) (ESnd e) = {!!} -- embed (ty ⊎ ty₁) (ECase e e₁ e₂) = {!!} embed (ty • ty₁) e = embed ty (EFst e) , embed ty₁ (ESnd e) embed {Γ} (AFun {α} ty₁ ty₂) e = λ Γ↝Γ' v₁ → embed ty₂ (EApp (liftE Γ↝Γ' e) (lift' ty₁ v₁)) -------------------- -- Partial Evaluator -------------------- pe : ∀ {α Δ Γ} → AExp Δ α → AEnv Γ Δ → Imp Γ α pe (Var x) env = lookup env x pe (AInt x) env = x pe (AAdd e e₁) env = pe e env + pe e₁ env pe (ALam {α} e) env = λ Γ↝Γ' → λ y → pe e (cons {α = α} y (liftEnv Γ↝Γ' env)) pe (AApp e e₁) env = pe e env ↝-refl (pe e₁ env) pe (DInt x) env = EInt x pe (DAdd e e₁) env = EAdd (pe e env) (pe e₁ env) pe (DLam {σ} e) env = ELam (pe e (consD σ env)) pe (DApp e e₁) env = EApp (pe e env) (pe e₁ env) pe {Γ = Γ} (e , e₁) env = pe {Γ = Γ} e env , pe {Γ = Γ} e₁ env pe {α = α₁ ⊎ α₂} {Γ = Γ} (Tl e) env = tl (pe {α = α₁} {Γ = Γ} e env) pe {α = α₁ ⊎ α₂} {Γ = Γ} (Tr e) env = tr (pe {α = α₂} {Γ = Γ} e env) pe {Γ = Γ} (Fst e) env = fst (pe {Γ = Γ} e env) pe {Γ = Γ} (Snd e) env = snd (pe {Γ = Γ} e env) pe {Γ = Γ} (Case e e₁ e₂) env with pe {Γ = Γ} e env pe {Γ = Γ} (Case {α₁ = α} e e₁ e₂) env | tl y = (λ Γ↝Γ' → λ y → pe e₁ (cons {α = α} y (liftEnv Γ↝Γ' env))) ↝-refl y pe {Γ = Γ} (Case {α₂ = α} e e₁ e₂) env | tr y = (λ Γ↝Γ' → λ y → pe e₂ (cons {α = α} y (liftEnv Γ↝Γ' env))) ↝-refl y pe (e ḋ e₁) env = pe e env , pe e₁ env pe (DTl e) env = Tl (pe e env) pe (DTr e) env = Tr (pe e env) pe (DFst e) env = EFst (pe e env) pe (DSnd e) env = ESnd (pe e env) pe (DCase {σ₁} {σ₂} e e₁ e₂) env = ECase (pe e env) (pe e₁ (consD σ₁ env)) (pe e₂ (consD σ₂ env)) pe (↑ x e) env = lift' x (pe e env) -- Correctness proof module Correctness where open SimpleAEnv open Exp-Eval -- TODO: rename occurences of stripα to typeof stripα = typeof stripΔ : ACtx → Ctx stripΔ = map stripα strip-lookup : ∀ { α Δ} → α ∈ Δ → stripα α ∈ stripΔ Δ strip-lookup hd = hd strip-lookup (tl x) = tl (strip-lookup x) strip : ∀ {α Δ} → AExp Δ α → Exp (stripΔ Δ) (stripα α) strip (Var x) = EVar (strip-lookup x) strip (AInt x) = EInt x strip (AAdd e e₁) = EAdd (strip e) (strip e₁) strip (ALam e) = ELam (strip e) strip (AApp e e₁) = EApp (strip e) (strip e₁) strip (DInt x) = EInt x strip (DAdd e e₁) = EAdd (strip e) (strip e₁) strip (DLam e) = ELam (strip e) strip (DApp e e₁) = EApp (strip e) (strip e₁) strip (e , e₁) = strip e , strip e₁ strip (Tl e) = Tl (strip e) strip (Tr e) = Tr (strip e) strip (Fst e) = EFst (strip e) strip (Snd e) = ESnd (strip e) strip (Case e e₁ e₂) = ECase (strip e) (strip e₁) (strip e₂) strip (e ḋ e₁) = strip e , strip e₁ strip (DTl e) = Tl (strip e) strip (DTr e) = Tr (strip e) strip (DFst e) = EFst (strip e) strip (DSnd e) = ESnd (strip e) strip (DCase e e₁ e₂) = ECase (strip e) (strip e₁) (strip e₂) strip (↑ x e) = strip e --liftE : ∀ {τ Γ Γ'} → Γ ↝ Γ' → Exp Γ τ → Exp Γ' τ --liftE Γ↝Γ' e = elevate (↝↝-base Γ↝Γ') e stripLift : ∀ {α Δ Γ} → stripΔ Δ ↝ Γ → AExp Δ α → Exp Γ (stripα α) stripLift Δ↝Γ = liftE Δ↝Γ ∘ strip -- -------------------------------- -- --""lift-strip"" equivalence lemma -- -------------------------------- -- ↑≡↓ : ∀ x e env env' aenv → Equiv-Env env' aenv env → ev (lift' x (pe e aenv)) env' ≡ ev (strip e) env -- ↑≡↓ x e env env' aenv eqenv = {!!} -- We want to show that pe preserves the semantics of the -- program. Roughly, Exp-Eval.ev-ing a stripped program is -- equivalent to first pe-ing a program and then Exp-Eval.ev-ing the -- result. But as the pe-result of a static function ``can do more'' -- than the (ev ∘ strip)ped function we need somthing more refined. module Equiv where open import Relation.Binary.PropositionalEquality -- Extending a value environment according to an extension of a -- type environment data _⊢_↝_ {Γ} : ∀ {Γ'} → Γ ↝ Γ' → Env Γ → Env Γ' → Set where refl : ∀ env → ↝-refl ⊢ env ↝ env extend : ∀ {τ Γ' env env'} → {Γ↝Γ' : Γ ↝ Γ'} → (v : EImp τ) → (Γ↝Γ' ⊢ env ↝ env') → ↝-extend {Γ = Γ} {Γ' = Γ'} {τ = τ} Γ↝Γ' ⊢ env ↝ (v ∷ env') env↝trans : ∀ {Γ Γ' Γ''} {Γ↝Γ' : Γ ↝ Γ'} {Γ'↝Γ'' : Γ' ↝ Γ''} {env env' env''} → Γ↝Γ' ⊢ env ↝ env' → Γ'↝Γ'' ⊢ env' ↝ env'' → let Γ↝Γ'' = ↝-trans Γ↝Γ' Γ'↝Γ'' in Γ↝Γ'' ⊢ env ↝ env'' env↝trans {Γ} {.Γ''} {Γ''} {Γ↝Γ'} {.↝-refl} {env} {.env''} {env''} env↝env' (refl .env'') = env↝env' env↝trans env↝env' (extend v env'↝env'') = extend v (env↝trans env↝env' env'↝env'') -- Equivalent Imp Γ α and EImp τ values (where τ = stripα α). As -- (v : Imp Γ α) is not necessarily closed, equivalence is defined for -- the closure (Env Γ, ImpΓ α) Equiv : ∀ {α Γ} → Env Γ → Imp Γ α → EImp (stripα α) → Set Equiv {AInt} env av v = av ≡ v Equiv {AFun α₁ α₂} {Γ} env av v = ∀ {Γ' env' Γ↝Γ'} → (Γ↝Γ' ⊢ env ↝ env') → {av' : Imp Γ' α₁} → {v' : EImp (stripα α₁)} → Equiv {α₁} {Γ'} env' av' v' → Equiv {α₂} env' (av Γ↝Γ' av') (v v') Equiv {D x} env av v = ev av env ≡ v Equiv {α • α₁} env (ffst , ssnd) (ffst₁ , ssnd₁) = (Equiv {α} env ffst ffst₁) ∧ (Equiv {α₁} env ssnd ssnd₁) Equiv {α ⊎ α₁} env (tl a) (tl a₁) = Equiv {α} env a a₁ -------------------------------------------------------------------- Equiv {α ⊎ α₁} env (tl a) (tr b) = ⊥ -- Interesting case! Equiv {α ⊎ α₁} env (tr b) (tl a) = ⊥ -- Interesting case! -------------------------------------------------------------------- Equiv {α ⊎ α₁} env (tr b) (tr b₁) = Equiv {α₁} env b b₁ -- Equiv {AInt} env av v = av ≡ v -- Equiv {AFun α₁ α₂} {Γ} env av v = -- extensional equality, given -- an extended context -- ∀ {Γ' env' Γ↝Γ'} → (Γ↝Γ' ⊢ env ↝ env') → -- {av' : Imp Γ' α₁} → {v' : EImp (stripα α₁)} → -- Equiv env' av' v' → Equiv env' (av Γ↝Γ' av') (v v') -- Equiv {D x} {Γ} env av v = ev av env ≡ v -- actually we mean extensional equality -- TODO: Define a proper equivalence for EImps -- Equivalence of AEnv and Env environments. They need to provide -- Equivalent bindings for a context Δ/stripΔ Δ. Again, the -- equivalence is defined for a closure (Env Γ', AEnv Γ' Δ). data Equiv-Env {Γ' : _} (env' : Env Γ') : ∀ {Δ} → let Γ = stripΔ Δ in AEnv Γ' Δ → Env Γ → Set where [] : Equiv-Env env' [] [] cons : ∀ {α Δ} → let τ = stripα α Γ = stripΔ Δ in {env : Env Γ} → {aenv : AEnv Γ' Δ} → Equiv-Env env' aenv env → (va : Imp (Γ') α) → (v : EImp τ) → Equiv {α} {Γ'} env' va v → --Equiv-Env env' (cons α va (aenv)) (v ∷ env) Equiv-Env env' (cons {α = α} va (aenv)) (v ∷ env) -------------------------------- --""lift-strip"" equivalence lemma -------------------------------- -- ↑≡↓ : ∀ {Γ' Δ α} x e env env' aenv → Equiv-Env {Γ'} env' {Δ} aenv env → ev (lift' {Γ = Γ'} {α = α} x (pe e aenv)) env' ≡ ev (strip e) env -- ↑≡↓ x e env env' aenv eqenv = {!!} -- Now for the proof... module Proof where open Equiv open import Relation.Binary.PropositionalEquality -- Extensional equality as an axiom to prove the Equivalence of -- function values. We could (should?) define it locally for -- Equiv. postulate ext : ∀ {τ₁ τ₂} {f g : EImp τ₁ → EImp τ₂} → (∀ x → f x ≡ g x) → f ≡ g -- Ternary helper relation for environment extensions, analogous to _↝_↝_ for contexts data _⊢_↝_↝_⊣ : ∀ { Γ Γ' Γ''} → Γ ↝ Γ' ↝ Γ'' → Env Γ → Env Γ' → Env Γ'' → Set where refl : ∀ {Γ Γ''} {Γ↝Γ'' : Γ ↝ Γ''} { env env'' } → Γ↝Γ'' ⊢ env ↝ env'' → ↝↝-base Γ↝Γ'' ⊢ env ↝ [] ↝ env'' ⊣ extend : ∀ {Γ Γ' Γ'' τ} {Γ↝Γ'↝Γ'' : Γ ↝ Γ' ↝ Γ''} { env env' env'' } → Γ↝Γ'↝Γ'' ⊢ env ↝ env' ↝ env'' ⊣ → (v : EImp τ) → ↝↝-extend {Γ = Γ} {Γ' = Γ'} {Γ'' = Γ''} {τ = τ} Γ↝Γ'↝Γ'' ⊢ (v ∷ env) ↝ (v ∷ env') ↝ (v ∷ env'') ⊣ -- the following lemmas are strong versions of the shifting -- functions, proving that consistent variable renaming preserves -- equivalence (and not just typing). lookup-elevate-≡ : ∀ {τ Γ Γ'} {Γ↝Γ' : Γ ↝ Γ'} {env : Env Γ} {env' : Env Γ'} → Γ↝Γ' ⊢ env ↝ env' → (x : τ ∈ Γ) → lookupE x env ≡ lookupE (elevate-var Γ↝Γ' x) env' lookup-elevate-≡ {τ} {.Γ'} {Γ'} {.↝-refl} {.env'} {env'} (refl .env') x = refl lookup-elevate-≡ (extend v env↝env') x = lookup-elevate-≡ env↝env' x lookup-elevate2-≡ : ∀ {τ Γ Γ' Γ''} {Γ↝Γ'↝Γ'' : Γ ↝ Γ' ↝ Γ''} {env : Env Γ} {env' : Env Γ'} {env'' : Env Γ''} → Γ↝Γ'↝Γ'' ⊢ env ↝ env' ↝ env'' ⊣ → (x : τ ∈ Γ) → lookupE x env ≡ lookupE (elevate-var2 Γ↝Γ'↝Γ'' x) env'' lookup-elevate2-≡ (refl Γ↝Γ') x = lookup-elevate-≡ Γ↝Γ' x lookup-elevate2-≡ (extend env↝env'↝env'' v) hd = refl lookup-elevate2-≡ (extend env↝env'↝env'' _) (tl x) rewrite lookup-elevate2-≡ env↝env'↝env'' x = refl lem-elevate-≡ : ∀ {τ Γ Γ' Γ''} {Γ↝Γ'↝Γ'' : Γ ↝ Γ' ↝ Γ''} {env : Env Γ} {env' : Env Γ'} {env'' : Env Γ''} → Γ↝Γ'↝Γ'' ⊢ env ↝ env' ↝ env'' ⊣ → (e : Exp Γ τ) → ev e env ≡ ev (elevate Γ↝Γ'↝Γ'' e) env'' lem-elevate-≡ env↝env' (EVar x) = lookup-elevate2-≡ env↝env' x lem-elevate-≡ env↝env' (EInt x) = refl lem-elevate-≡ env↝env' (EAdd e e₁) with lem-elevate-≡ env↝env' e | lem-elevate-≡ env↝env' e₁ ... | IA1 | IA2 = cong₂ _+_ IA1 IA2 lem-elevate-≡ {Fun τ₁ τ₂} {Γ↝Γ'↝Γ'' = Γ↝Γ'↝Γ''} {env = env} {env'' = env''} env↝env' (ELam e) = ext {τ₁} {τ₂} lem-elevate-≡-body where lem-elevate-≡-body : ∀ x → ev e (x ∷ env) ≡ ev (elevate (↝↝-extend Γ↝Γ'↝Γ'') e) (x ∷ env'') lem-elevate-≡-body x = lem-elevate-≡ (extend env↝env' x) e lem-elevate-≡ env↝env' (EApp e e₁) with lem-elevate-≡ env↝env' e | lem-elevate-≡ env↝env' e₁ ... | IA1 | IA2 = cong₂ (λ f₁ x → f₁ x) IA1 IA2 lem-elevate-≡ env↝env' (e , e₁) with lem-elevate-≡ env↝env' e | lem-elevate-≡ env↝env' e₁ ... | IA1 | IA2 = cong₂ (λ x y → x , y) IA1 IA2 lem-elevate-≡ env↝env' (Tl e) with lem-elevate-≡ env↝env' e ... | IA = cong (λ x → tl x) IA lem-elevate-≡ env↝env' (Tr e) with lem-elevate-≡ env↝env' e ... | IA = cong (λ x → tr x) IA lem-elevate-≡ env↝env' (EFst e) with lem-elevate-≡ env↝env' e ... | IA = cong (λ x → fst x) IA lem-elevate-≡ env↝env' (ESnd e) with lem-elevate-≡ env↝env' e ... | IA = cong (λ x → snd x) IA lem-elevate-≡ {Γ↝Γ'↝Γ'' = Γ↝Γ'↝Γ''} {env = env} {env'' = env''} env↝env' (ECase e e₁ e₂) with ev e env | ev (elevate Γ↝Γ'↝Γ'' e) env'' | lem-elevate-≡ env↝env' e ... | tl c | tl c' | IA rewrite (→tl {x' = c} {y' = c'} (tl c) (tl c') IA refl refl) = lem-elevate-≡-body c' where lem-elevate-≡-body : ∀ x → ev e₁ (x ∷ env) ≡ ev (elevate (↝↝-extend Γ↝Γ'↝Γ'') e₁) (x ∷ env'') lem-elevate-≡-body x = lem-elevate-≡ (extend env↝env' x) e₁ ... | tl c | tr c' | () ... | tr c | tl c' | () ... | tr c | tr c' | IA rewrite (→tr {x' = c} {y' = c'} (tr c) (tr c') IA refl refl) = lem-elevate-≡-body c' where lem-elevate-≡-body : ∀ x → ev e₂ (x ∷ env) ≡ ev (elevate (↝↝-extend Γ↝Γ'↝Γ'') e₂) (x ∷ env'') lem-elevate-≡-body x = lem-elevate-≡ (extend env↝env' x) e₂ lem-lift-refl-id : ∀ {α Γ} → let τ = stripα α in (env : Env Γ) → (v : EImp τ) (va : Imp Γ α) → Equiv {α} {Γ} env va v → Equiv {α} {Γ} env (lift α ↝-refl va) v lem-lift-refl-id {AInt} env v va eq = eq lem-lift-refl-id {AFun α α₁} {Γ} env v va eq = body where body : ∀ {Γ'} {env' : Env Γ'} {Γ↝Γ' : Γ ↝ Γ'} → Γ↝Γ' ⊢ env ↝ env' → {av' : Imp Γ' α} {v' : EImp (stripα α)} → Equiv {α} {Γ'} env' av' v' → Equiv {α₁} {Γ'} env' (va (↝-trans ↝-refl Γ↝Γ') av') (v v') body {Γ↝Γ' = Γ↝Γ'} env↝env' eq' rewrite sym (lem-↝-refl-id Γ↝Γ') = eq env↝env' eq' lem-lift-refl-id {D x} env v va eq rewrite sym eq = sym (lem-elevate-≡ (refl (refl env)) va) lem-lift-refl-id {α • α₁} env (ffst , ssnd) (ffst₁ , ssnd₁) (∧-intro x x₁) = ∧-intro (lem-lift-refl-id {α} env ffst ffst₁ x) (lem-lift-refl-id {α₁} env ssnd ssnd₁ x₁) lem-lift-refl-id {α ⊎ α₁} env (tl a) (tl a₁) eq = lem-lift-refl-id {α} env a a₁ eq lem-lift-refl-id {α ⊎ α₁} env (tl a) (tr b) () lem-lift-refl-id {α ⊎ α₁} env (tr b) (tl a) () lem-lift-refl-id {α ⊎ α₁} env (tr b) (tr b₁) eq = lem-lift-refl-id {α₁} env b b₁ eq -- lifting an Imp does not affect equivalence lem-lift-equiv : ∀ {α Γ Γ'} → let τ = stripα α in {Γ↝Γ' : Γ ↝ Γ'} → (va : Imp Γ α) (v : EImp τ) → {env : Env Γ} {env' : Env Γ'} → Γ↝Γ' ⊢ env ↝ env' → Equiv {α} {Γ} env va v → Equiv {α} {Γ'} env' (lift α Γ↝Γ' va) v lem-lift-equiv {α} va v {.env'} {env'} (refl .env') eq = lem-lift-refl-id {α} env' v va eq lem-lift-equiv {AInt} va v (extend v₁ env↝env') eq = eq lem-lift-equiv {AFun α α₁} va v (extend v₁ env↝env') eq = λ v₁env₁↝env' eq₁ → eq (env↝trans (extend v₁ env↝env') v₁env₁↝env') eq₁ lem-lift-equiv {D x} va v (extend v₁ env↝env') eq rewrite sym eq = sym (lem-elevate-≡ (refl (extend v₁ env↝env')) va) lem-lift-equiv {α • α₁} (ffst , ssnd) (ffst₁ , ssnd₁) (extend v₁ env↝env') (∧-intro x x₁) = ∧-intro (lem-lift-equiv {α} ffst ffst₁ (extend v₁ env↝env') x) (lem-lift-equiv {α₁} ssnd ssnd₁ (extend v₁ env↝env') x₁) lem-lift-equiv {α ⊎ α₁} (tl a) (tl a₁) (extend v₁ env↝env') eq = lem-lift-equiv {α} a a₁ (extend v₁ env↝env') eq lem-lift-equiv {α ⊎ α₁} (tl a) (tr b) (extend v₁ env↝env') () lem-lift-equiv {α ⊎ α₁} (tr b) (tl a) (extend v₁ env↝env') () lem-lift-equiv {α ⊎ α₁} (tr b) (tr b₁) (extend v₁ env↝env') eq = lem-lift-equiv {α₁} b b₁ (extend v₁ env↝env') eq lem-equiv-lookup : ∀ {α Δ Γ'} → let Γ = stripΔ Δ in { aenv : AEnv Γ' Δ } {env : Env Γ} → (env' : Env Γ') → Equiv-Env env' aenv env → ∀ (x : α ∈ Δ) → Equiv {α} env' (lookup aenv x) (lookupE (strip-lookup x) env) lem-equiv-lookup env' [] () lem-equiv-lookup env' (cons enveq va v eq) hd = eq lem-equiv-lookup env' (cons enveq va v eq) (tl x) = lem-equiv-lookup env' enveq x lem-equiv-env-lift-extend : ∀ {σ Γ' Δ} (env' : Env Γ') → let Γ = stripΔ Δ in {env : Env Γ} {aenv : AEnv Γ' Δ} → Equiv-Env env' aenv env → (x : EImp σ) → Equiv-Env {σ ∷ Γ'} (x ∷ env') (liftEnv (↝-extend ↝-refl) aenv) env lem-equiv-env-lift-extend _ [] x = [] lem-equiv-env-lift-extend env' (cons {α} eqenv va v x) x₁ = cons (lem-equiv-env-lift-extend env' eqenv x₁) (lift α (↝-extend ↝-refl) va) v (lem-lift-equiv {α} va v (extend x₁ (refl env')) x) lem-equiv-env-lift-lift : ∀ {Γ' Γ'' Δ} → let Γ = stripΔ Δ in {Γ↝Γ' : Γ' ↝ Γ''} {env' : Env Γ'} {env'' : Env Γ''} (env'↝env'' : Γ↝Γ' ⊢ env' ↝ env'') → {env : Env Γ} {aenv : AEnv Γ' Δ} → Equiv-Env env' aenv env → Equiv-Env env'' (liftEnv Γ↝Γ' aenv) env lem-equiv-env-lift-lift env'↝env'' [] = [] lem-equiv-env-lift-lift {Γ↝Γ' = Γ↝Γ'} env'↝env'' (cons {α} eqenv va v x) with lem-equiv-env-lift-lift env'↝env'' eqenv ... | IA = cons IA (lift α Γ↝Γ' va) v (lem-lift-equiv {α} va v env'↝env'' x) -------------------------------- --""lift-correct"" equivalence lemma -------------------------------- open import Data.Product mutual lift-correct : ∀ {Γ α} (lft : Liftable α) (env : Env Γ) (av : Imp Γ α) (v : EImp (typeof α)) → Equiv {α} {Γ} env av v → (Equiv {D (typeof α)} {Γ} env (lift' lft av) v) lift-correct (D τ) env av v eq = eq lift-correct AInt env av v eq = eq lift-correct (lft ⊎ lft₁) env (tl a) (tl a₁) eq with lift-correct lft env a a₁ ... | IA rewrite IA eq = refl lift-correct (lft ⊎ lft₁) env (tr b) (tl a) () lift-correct (lft ⊎ lft₁) env (tl a) (tr b) () lift-correct (lft ⊎ lft₁) env (tr b) (tr b₁) eq with lift-correct lft₁ env b b₁ ... | IA rewrite IA eq = refl lift-correct (lft • lft₁) env (ffst , ssnd) (ffst₁ , ssnd₁) (∧-intro x x₁) rewrite lift-correct lft env ffst ffst₁ x | lift-correct lft₁ env ssnd ssnd₁ x₁ = refl lift-correct {Γ} {AFun x lft} (AFun y y') env av v eq = ext {typeof x} {typeof lft} (λ x₁ → lift-correct y' (x₁ ∷ env) (av (↝-extend ↝-refl) (embed y (EVar hd))) (v x₁) (eq (extend x₁ (refl env)) (embed-correct {typeof x ∷ Γ} {x} y (x₁ ∷ env) (EVar hd) x₁ refl))) embed-correct : ∀ {Γ α} (lft : Liftable⁻ α) (env : Env Γ) → (e : Exp Γ (typeof α)) → (v : EImp (typeof α)) → ev e env ≡ v → Equiv {α} {Γ} env (embed lft e) v embed-correct (D τ) env e v eq rewrite eq = refl embed-correct (lft • lft₁) env e (fstv , sndv) eq = ∧-intro (embed-correct lft env (EFst e) fstv (subst (λ x → ffst x ≡ fstv) (sym eq) refl)) (embed-correct lft₁ env (ESnd e) sndv (subst (λ x → ssnd x ≡ sndv) (sym eq) refl)) embed-correct {α = AFun α₁ α₂} (AFun x lft) env e v eq = f where f : ∀ {Γ' env' Γ↝Γ'} (x₁ : Γ↝Γ' ⊢ env ↝ env') {x₂ : Imp Γ' α₁} {x₃ : EImp (typeof α₁)} (x₄ : Equiv {α₁} {Γ'} env' x₂ x₃) → Equiv {α₂} {Γ'} env' (embed lft (EApp (elevate (↝↝-base Γ↝Γ') e) (lift' x x₂))) (v x₃) f {Γ'} {env'} {Γext} envext {av'} {v'} eq' = embed-correct lft env' (EApp (elevate (↝↝-base Γext) e) (lift' x av')) (v v') g where g : ev (elevate (↝↝-base Γext) e) env' (ev (lift' x av') env') ≡ v v' g rewrite lift-correct x env' av' v' eq' | sym (cong (λ f → f v') (lem-elevate-≡ (refl envext) e)) | (cong (λ f → f v') eq) = refl --g = {!!} --------------------------------------- --Correctness proof with liftable terms --------------------------------------- -- When we partially evaluate somthing under an environment , it -- will give equivalent results to a ``complete'' evaluation under -- an equivalent environment pe-correct : ∀ { α Δ Γ' } → (e : AExp Δ α) → let Γ = stripΔ Δ in {aenv : AEnv Γ' Δ} → {env : Env Γ} → (env' : Env Γ') → Equiv-Env env' aenv env → Equiv {α} {Γ'} env' (pe e aenv) (ev (strip e) env) pe-correct (Var x) env' eqenv = lem-equiv-lookup env' eqenv x pe-correct (AInt x) env' eqenv = refl pe-correct (AAdd e e₁) env' eqenv rewrite pe-correct e env' eqenv | pe-correct e₁ env' eqenv = refl pe-correct (ALam e) env' eqenv = λ {_} {env''} env'↝env'' {av'} {v'} eq → let eqenv' : _ eqenv' = lem-equiv-env-lift-lift env'↝env'' eqenv eqenv'' : _ eqenv'' = cons eqenv' av' v' eq in pe-correct e env'' eqenv'' pe-correct (AApp e e₁) env' eqenv with pe-correct e env' eqenv | pe-correct e₁ env' eqenv ... | IAe | IAf = IAe (refl env') IAf pe-correct (DInt x) env' eqenv = refl pe-correct (DAdd e e₁) env' eqenv rewrite pe-correct e env' eqenv | pe-correct e₁ env' eqenv = refl pe-correct {α = D (Fun σ₁ σ₂)} (DLam e) env' eqenv = ext {σ₁} {σ₂} (λ x → let eqenv₁ : _ eqenv₁ = lem-equiv-env-lift-extend env' eqenv x eqenv₂ : _ eqenv₂ = cons eqenv₁ (EVar hd) x refl in pe-correct e (x ∷ env') eqenv₂) pe-correct (DApp e e₁) env' eqenv with pe-correct e₁ env' eqenv | pe-correct e env' eqenv ... | IA' | IA = cong₂ (λ f x → f x) IA IA' pe-correct (e , e₁) env' eqenv = ∧-intro (pe-correct e env' eqenv) (pe-correct e₁ env' eqenv) pe-correct (Tl e) env' eqenv = pe-correct e env' eqenv pe-correct (Tr e) env' eqenv = pe-correct e env' eqenv pe-correct (Fst (e , e₁)) env' eqenv = pe-correct e env' eqenv pe-correct (Fst e) {aenv = aenv} {env = env} env' eqenv with pe e aenv | ev (strip e) env | pe-correct e env' eqenv ... | e₁ , e₂ | e₁' , e₂' | ∧-intro A B = A pe-correct (Snd (e , e₁)) env' eqenv = pe-correct e₁ env' eqenv pe-correct (Snd e) {aenv = aenv} {env = env} env' eqenv with pe e aenv | ev (strip e) env | pe-correct e env' eqenv ... | e₁ , e₂ | e₁' , e₂' | ∧-intro A B = B pe-correct {α} (Case e e₁ e₂) {aenv = aenv} {env = env} env' eqenv with pe e aenv | ev (strip e) env | pe-correct e env' eqenv ... | tl c | tl c' | L = pe-correct e₁ {aenv = cons c (liftEnv ↝-refl aenv)} {env = c' ∷ env} env' (cons (lem-equiv-env-lift-lift (refl env') eqenv) c c' L) ... | tr c | tr c' | R = pe-correct e₂ {aenv = cons c (liftEnv ↝-refl aenv)} {env = c' ∷ env} env' (cons (lem-equiv-env-lift-lift (refl env') eqenv) c c' R) ... | tr c | tl c' | () ... | tl c | tr c' | () pe-correct (e ḋ e₁) env' eqenv with pe-correct e env' eqenv | pe-correct e₁ env' eqenv ... | IA | IA' rewrite IA | IA' = refl pe-correct (DTl e) env' eqenv with pe-correct e env' eqenv ... | IA rewrite IA = refl pe-correct (DTr e) env' eqenv with pe-correct e env' eqenv ... | IA rewrite IA = refl pe-correct (DFst e) env' eqenv with pe-correct e env' eqenv ... | IA rewrite IA = refl pe-correct (DSnd e) env' eqenv with pe-correct e env' eqenv ... | IA rewrite IA = refl pe-correct (DCase e e₁ e₂) {aenv = aenv} {env = env} env' eqenv with ev (pe e aenv) env' | ev (strip e) env | pe-correct e env' eqenv ... | tl c | tl c' | IA rewrite (→tl {x' = c} {y' = c'} (tl c) (tl c') IA refl refl) = pe-correct e₁ {aenv = cons (EVar hd) (liftEnv (↝-extend ↝-refl) aenv)} {env = c' ∷ env} (c' ∷ env') (cons (lem-equiv-env-lift-lift (extend c' (refl env')) eqenv) (EVar hd) c' refl) ... | tr c | tr c' | IA rewrite (→tr {x' = c} {y' = c'} (tr c) (tr c') IA refl refl) = pe-correct e₂ {aenv = cons (EVar hd) (liftEnv (↝-extend ↝-refl) aenv)} {env = c' ∷ env} (c' ∷ env') (cons (lem-equiv-env-lift-lift (extend c' (refl env')) eqenv) (EVar hd) c' refl) ... | tl c | tr c' | () ... | tr c | tl c' | () pe-correct (↑ x e) {aenv = aenv} {env = env} env' eqenv with pe-correct e env' eqenv ... | IA = lift-correct x env' (pe e aenv) (ev (strip e) env) IA ",16255,True,2959.1524409124227,median "{-# OPTIONS --cubical --no-import-sorts --allow-unsolved-metas #-} module Number.Operations.Details where open import Cubical.Foundations.Everything renaming (_⁻¹ to _⁻¹ᵖ; assoc to ∙-assoc) open import Cubical.Relation.Nullary.Base -- ¬_ open import Cubical.Data.Unit.Base -- Unit open import Cubical.Data.Sigma.Base renaming (_×_ to infixr 4 _×_) open import Cubical.Data.Empty renaming (elim to ⊥-elim) -- `⊥` and `elim` open import Function.Base using (_$_) open import Cubical.Data.Nat.Properties open import Cubical.Data.Nat.Order renaming (zero-≤ to z≤n; suc-≤-suc to s≤s) open import MoreNatProperties renaming (0≤x to 0≤xⁿ) open import Number.Postulates open import Number.Structures open import Number.Bundles open import Number.Inclusions open import Number.Base open import Number.Coercions open ℕⁿ open ℤᶻ open ℚᶠ open ℝʳ open ℂᶜ infix 9 _⁻¹ infix 8 -_ open import Number.Operations.Specification open PatternsProp _⁻¹ : ∀{l p} → (x : Number (l , p)) → ⁻¹-Types x _⁻¹ {isNat } {⁇x⁇} (x ,, q) {{h}} = let r = Isℕ↪ℚ.preserves-#0 ℕ↪ℚinc _ h in _⁻¹ᶠ (ℕ↪ℚ x) {{r}} ,, ℚ.⁻¹-preserves-#0 _ r _⁻¹ {isNat } {x#0} (x ,, q) {{h}} = let r = Isℕ↪ℚ.preserves-#0 ℕ↪ℚinc _ q in _⁻¹ᶠ (ℕ↪ℚ x) {{r}} ,, ℚ.⁻¹-preserves-#0 _ r _⁻¹ {isNat } {0≤x} (x ,, q) {{h}} = let p = Isℕ↪ℚ.preserves-0< ℕ↪ℚinc _ (ℕ.≤-#-implies-< _ _ q (ℕ.#-sym _ _ h)) r = Isℕ↪ℚ.preserves-#0 ℕ↪ℚinc _ h in _⁻¹ᶠ (ℕ↪ℚ x) {{r}} ,, ℚ.⁻¹-preserves-0< _ p r _⁻¹ {isNat } {0 0) { return ""+"" + LocText.current.text(""general/reward/honor_name"",param1); } return LocText.current.text(""general/reward/honor_name"",param1); } public static function getArtifactString(param1:int) : String { return LocText.current.text(""general/reward/artifact_name"",param1); } public static function getXpString(param1:int) : String { return LocText.current.text(""general/reward/xp_name"",LocText.current.formatHugeNumber(param1)); } public static function getStatPointString(param1:int) : String { return LocText.current.text(""general/reward/stat_point_name"",param1); } public static function getGameCurrencyString(param1:int) : String { return LocText.current.text(""general/reward/coins_name"",param1); } public static function getPremiumCurrencyString(param1:int) : String { return LocText.current.text(""general/reward/premium_currency_name"",param1); } public static function getGuildPremiumCurrencyString(param1:int) : String { return LocText.current.text(""general/reward/guild_premium_currency_name"",param1); } public static function getEnergyString(param1:int) : String { return LocText.current.text(""general/energy_name"",param1); } public static function getMovieEnergyString(param1:int) : String { return LocText.current.text(""general/movie_energy"",LocText.current.formatHugeNumber(param1)); } public static function getMovieProgressString(param1:int) : String { return LocText.current.text(""general/movie_progress"",LocText.current.formatHugeNumber(param1)); } public static function getLevelString(param1:int) : String { return LocText.current.text(""general/level"",param1); } public static function getItemCountString(param1:int) : String { return LocText.current.text(""general/item"",param1); } public static function getGuildMissileString(param1:int) : String { return LocText.current.text(""general/guild/missile"",param1); } public static function getGuildAutoJoinsString(param1:int) : String { return LocText.current.text(""general/guild/auto_joins"",param1); } public static function getGuildMemberCountString(param1:int) : String { return LocText.current.text(""general/guild/member"",param1); } public static function getGuildBattleCountString(param1:int) : String { return LocText.current.text(""general/guild/battle"",param1); } public static function getSlotmachineJetonCountString(param1:int) : String { return LocText.current.text(""general/slot_machine/jetons"",param1,CConstant.resource_slotmachine_jeton_usage_amount); } public static function getOpticalChangeResourceString(param1:int) : String { return LocText.current.text(""general/optical_change_resource_name"",param1); } public static function getFanFotoResourceString(param1:int) : String { return LocText.current.text(""general/fan_foto_resource_name"",param1); } public static function getStreamingResourceString(param1:int) : String { return LocText.current.text(""general/streaming_resource_name"",LocText.current.formatHugeNumber(param1)); } public static function getFansString(param1:int) : String { return LocText.current.text(""general/fans_name"",LocText.current.formatHugeNumber(param1)); } public static function getQuestInstantFinishCost(param1:int) : int { if(param1 < CConstant.quest_instant_finish_range1_duration * 60) { return CConstant.quest_instant_finish_range1_premium_amount; } if(param1 < CConstant.quest_instant_finish_range2_duration * 60) { return CConstant.quest_instant_finish_range2_premium_amount; } if(param1 < CConstant.quest_instant_finish_range3_duration * 60) { return CConstant.quest_instant_finish_range3_premium_amount; } return CConstant.quest_instant_finish_range4_premium_amount; } public static function duelHonorWinReward(param1:int, param2:int) : int { var _loc5_:Number = CConstant.pvp_honor_win_exp_better; var _loc3_:Number = CConstant.pvp_honor_win_exp_worse; var _loc4_:* = 0; if(param1 > param2) { _loc4_ = Number(1 - Math.pow(param2 / param1,_loc3_)); } else { _loc4_ = Number(-1 * (1 - Math.pow(param1 / param2,_loc5_))); } _loc4_ = Number(100 - _loc4_ * 100); return Math.round(_loc4_); } public static function duelHonorLostReward(param1:int, param2:int) : int { if(param1 == 0) { return 0; } var _loc4_:Number = CConstant.pvp_honor_lose_amount; var _loc6_:Number = CConstant.pvp_honor_lose_max; var _loc5_:Number = duelHonorWinReward(param1,param2); var _loc7_:* = 0; if(_loc4_ * _loc5_ < _loc6_ * param2) { _loc7_ = Number(_loc4_ * _loc5_); } else { _loc7_ = Number(_loc6_ * param2); } var _loc3_:int = Math.round(_loc7_); _loc3_ = _loc3_ * -1; return _loc3_; } public static function duelGameCurrencyWinReward(param1:int) : int { var _loc3_:Number = CConstant.pvp_waiting_time; var _loc2_:Number = CConstant.pvp_effectiveness_won; var _loc4_:Number = _loc3_ * gameCurrencyPerTime(param1) * _loc2_; return Math.round(_loc4_); } public static function gameCurrencyCostEnergyRefill(param1:int, param2:int) : int { var _loc4_:int = param2 / CConstant.quest_energy_refill_amount; var _loc3_:int = 0; switch(int(_loc4_)) { case 0: _loc3_ = CConstant.quest_energy_refill1_cost_factor; break; case 1: _loc3_ = CConstant.quest_energy_refill2_cost_factor; break; case 2: _loc3_ = CConstant.quest_energy_refill3_cost_factor; break; case 3: _loc3_ = CConstant.quest_energy_refill4_cost_factor; } var _loc5_:Number = _loc3_ * gameCurrencyPerTime(param1); return Math.round(_loc5_); } public static function premiumCostEnergyRefill(param1:int) : int { var _loc2_:* = 1; if(param1 <= CConstant.quest_energy_refill_discount_1_max_level) { _loc2_ = Number(CConstant.quest_energy_refill_premium_amount_discount_1); } else if(param1 <= CConstant.quest_energy_refill_discount_2_max_level) { _loc2_ = Number(CConstant.quest_energy_refill_premium_amount_discount_2); } else if(param1 <= CConstant.quest_energy_refill_discount_3_max_level) { _loc2_ = Number(CConstant.quest_energy_refill_premium_amount_discount_3); } var _loc3_:int = Math.round(CConstant.quest_energy_refill_premium_amount * _loc2_); return _loc3_; } public static function getEnergyRefillDiscountMaxLevel(param1:int) : int { if(param1 <= CConstant.quest_energy_refill_discount_1_max_level) { return CConstant.quest_energy_refill_discount_1_max_level + 1; } if(param1 <= CConstant.quest_energy_refill_discount_2_max_level) { return CConstant.quest_energy_refill_discount_2_max_level + 1; } if(param1 <= CConstant.quest_energy_refill_discount_3_max_level) { return CConstant.quest_energy_refill_discount_3_max_level + 1; } return 0; } public static function getGoalRewardAmount(param1:int, param2:Number, param3:int) : int { var _loc11_:Number = NaN; var _loc10_:Number = NaN; var _loc5_:Number = NaN; var _loc8_:int = 0; var _loc7_:int = 0; var _loc9_:int = 0; var _loc6_:Number = NaN; var _loc4_:* = 0; switch(int(param1) - 1) { case 0: _loc11_ = gameCurrencyPerTime(param3); _loc10_ = CConstant.goal_reward_game_currency_time; _loc5_ = CConstant.goal_reward_game_currency_percentage_base; _loc5_ = _loc5_ * param2; _loc11_ = Math.round(_loc11_ * _loc5_ * _loc10_); _loc11_ = _loc11_ + Math.pow(param3,CConstant.goal_reward_game_currency_exp); return Math.round(_loc11_); case 1: _loc4_ = Number(CConstant.goal_reward_premium_currency_base); _loc4_ = Number(_loc4_ * param2); return Math.round(_loc4_); case 2: _loc4_ = Number(CConstant.goal_reward_stat_points_base); _loc4_ = Number(_loc4_ * param2); return Math.round(_loc4_); case 3: if(param3 >= CConstant.max_level) { return 0; } _loc8_ = CLevel.fromId(param3).xp; _loc7_ = CLevel.fromId(param3 + 1).xp; _loc9_ = _loc7_ - _loc8_; _loc6_ = CConstant.goal_reward_xp_percentage_base; _loc6_ = _loc6_ * param2; return Math.round(_loc9_ * _loc6_); case 4: return 0; case 5: case 6: _loc4_ = Number(CConstant.goal_reward_energy_base); _loc4_ = Number(_loc4_ * param2); return Math.round(_loc4_); } } public static function getItemPatternRewardAmount(param1:int, param2:Number) : int { var _loc3_:int = 0; switch(int(param1) - 1) { case 0: _loc3_ = CConstant.item_pattern_reward_stat_points_base; _loc3_ = _loc3_ * Math.round(param2); return _loc3_; case 1: return 0; case 2: _loc3_ = CConstant.item_pattern_reward_energy_base; _loc3_ = _loc3_ * Math.round(param2); return _loc3_; } } public static function guildBattleCost(param1:Number) : int { var _loc2_:int = CGuildBattleAttackCost.fromId(Math.floor(param1)).gameCurrencyCost; return _loc2_; } public static function guildBattleHonorWinReward(param1:int, param2:int) : int { return duelHonorWinReward(param1,param2) * 10; } public static function guildBattleHonorLostReward(param1:int, param2:int) : int { return duelHonorLostReward(param1,param2) * 10; } public static function roundDuration(param1:int) : int { if(param1 < 60) { return 60; } var _loc3_:int = 60; var _loc2_:int = param1 % _loc3_; if(_loc2_ == 0) { return param1; } if(_loc2_ < _loc3_ / 2) { return param1 - _loc2_; } return param1 - _loc2_ + _loc3_; } public static function getConventionShowInstantFinishCost(param1:int) : int { return CConstant.convention_instant_finish_premium_amount * param1; } public static function getHint(param1:int) : String { var _loc4_:* = null; var _loc2_:Vector. = new Vector.(); var _loc6_:int = 0; var _loc5_:* = CHint.ids; for each(var _loc3_ in CHint.ids) { _loc4_ = CHint.fromId(_loc3_); if(_loc4_.requiredLevel <= param1 && (_loc4_.maxLevel >= param1 || _loc4_.maxLevel == 0)) { _loc2_.push(_loc3_); } } _loc2_.sort(shuffleVector); return LocText.current.text(""hint/"" + _loc2_.pop() + ""/text""); } private static function shuffleVector(param1:Object, param2:Object) : int { return Math.floor(Math.random() * 3 - 1); } public static function matchesRef(param1:String, param2:String, param3:String) : Boolean { return param1.indexOf(param2) === 0 && param1.charAt(param1.length - 4) === ""-"" && param1.charAt(param1.length - 3) === param3; } public static function itemPatternSewPrice(param1:int, param2:int, param3:int) : int { var _loc4_:Number = NaN; if(param1 == 1) { _loc4_ = param2 * CConstant.sewing_machine_common_game_currency_factor; return Math.round(_loc4_); } var _loc5_:* = param3; if(_loc5_ == 0) { switch(int(param1) - 2) { case 0: _loc5_ = int(CConstant.sewing_machine_rare_premium_currency_amount); break; case 1: _loc5_ = int(CConstant.sewing_machine_epic_premium_currency_amount); } } return _loc5_; } public static function getQuestRefreshCost(param1:Boolean, param2:int) : int { var _loc4_:int = CConstant.quest_refresh_single_stage_premium_currency_amount; var _loc3_:Number = CConstant.quest_refresh_all_stages_reduction_factor; if(!param1) { return _loc4_; } return Math.round(_loc4_ + param2 * _loc3_); } public static function getStatString(param1:int, param2:int) : String { switch(int(param1) - 1) { case 0: return LocText.current.formatHugeNumber(param2) + "" "" + getStatName(param1); case 1: return LocText.current.formatHugeNumber(param2) + "" "" + getStatName(param1); case 2: return LocText.current.formatHugeNumber(param2) + "" "" + getStatName(param1); case 3: return LocText.current.formatHugeNumber(param2) + "" "" + getStatName(param1); case 4: return LocText.current.formatHugeNumber(param2) + "" "" + getStatName(param1); case 5: return LocText.current.formatHugeNumber(param2) + "" "" + getStatName(param1); } } public static function getStatName(param1:int) : String { switch(int(param1) - 1) { case 0: return LocText.current.text(""general/stat_stamina""); case 1: return LocText.current.text(""general/stat_strength""); case 2: return LocText.current.text(""general/stat_critical_rating""); case 3: return LocText.current.text(""general/stat_dodge_rating""); case 4: return LocText.current.text(""general/stat_weapon_damage""); case 5: return LocText.current.text(""general/stat_missile_damage""); } } public static function questGameCurrencyReward(param1:int, param2:int, param3:int, param4:Number = 1, param5:Number = 0) : int { if(param2 == 1) { return 5; } var _loc6_:* = 0; switch(int(param3) - 1) { case 0: _loc6_ = Number(CConstant.quest_reward_coin_scale_balanced); break; case 1: _loc6_ = Number(CConstant.quest_reward_coin_scale_xp_heavy); break; case 2: _loc6_ = Number(CConstant.quest_reward_coin_scale_coin_heavy); break; case 3: _loc6_ = Number(CConstant.quest_reward_coin_scale_item); } var _loc7_:Number = param1 * gameCurrencyPerTime(param2) * _loc6_ * param4; return Math.round(_loc7_ * (1 + param5)); } public static function getCustomBannerRewardAmount(param1:String, param2:Object, param3:int) : int { var _loc4_:* = param1; if(""game_currency"" !== _loc4_) { return 0; } return questGameCurrencyReward(param2 as int,param3,1,1,0); } public static function getCustomBannerRewardString(param1:String, param2:Object, param3:int) : String { var _loc4_:* = param1; if(""game_currency"" !== _loc4_) { return null; } return LocText.current.text(""custom_banner/game_currency_reward"",LocText.current.formatHugeNumber(getCustomBannerRewardAmount(param1,param2,param3))); } public static function doesItemNeedGenderSuffix(param1:String) : Boolean { var _loc2_:CItemTemplate = CItemTemplate.fromId(param1); if(!_loc2_) { return false; } var _loc3_:String = _loc2_.gender; if(_loc3_ == ""u"") { return false; } return true; } public static function compressAvatarImageSettings(param1:AppearanceSettings, param2:Vector.) : String { var _loc9_:int = 0; var _loc14_:* = null; var _loc4_:String = param1.gender; var _loc5_:String = ""g:"" + _loc4_ + "";""; var _loc12_:* = 0; var _loc3_:Array = [""hair_type"",""hair_color"",""eyebrows_type"",""facial_hair_type"",""decoration_type""]; _loc9_ = 0; while(_loc9_ < _loc3_.length) { _loc12_ = _loc12_ | param1.getInt(_loc3_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""b:"" + _loc12_ + "";""); _loc12_ = 0; var _loc8_:Array = [""eyebrows_color"",""facial_hair_color""]; _loc9_ = 0; while(_loc9_ < _loc8_.length) { _loc12_ = _loc12_ | param1.getInt(_loc8_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""b2:"" + _loc12_ + "";""); _loc12_ = 0; var _loc11_:Array = [""skin_color"",""head_type"",""eyes_type"",""nose_type"",""mouth_type""]; _loc9_ = 0; while(_loc9_ < _loc11_.length) { _loc12_ = _loc12_ | param1.getInt(_loc11_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""s:"" + _loc12_ + "";""); _loc12_ = 0; var _loc13_:Array = [""tattoo_arm_left"",""tattoo_arm_right"",""tattoo_body"",""tattoo_leg_left"",""tattoo_leg_right""]; _loc9_ = 0; while(_loc9_ < _loc13_.length) { _loc12_ = _loc12_ | param1.getInt(_loc13_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""tt:"" + _loc12_ + "";""); _loc12_ = 0; var _loc6_:Array = [""bra_type"",""panties_type"",""genitals_type"",""genitals_hair_type"",""genitals_hair_color""]; _loc9_ = 0; while(_loc9_ < _loc6_.length) { _loc12_ = _loc12_ | param1.getInt(_loc6_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""uw:"" + _loc12_ + "";""); _loc12_ = 0; var _loc15_:Array = [""photo_rect_type"",""photo_border_type"",""photo_background_type"",""photo_filter_type"",""photo_icon_type""]; _loc9_ = 0; while(_loc9_ < _loc15_.length) { _loc12_ = _loc12_ | param1.getInt(_loc15_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""p:"" + _loc12_ + "";""); _loc12_ = 0; var _loc7_:Array = [""photo_sexuality_type""]; _loc9_ = 0; while(_loc9_ < _loc7_.length) { _loc12_ = _loc12_ | param1.getInt(_loc7_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""p2:"" + _loc12_ + "";""); var _loc17_:int = 0; var _loc16_:* = param2; for each(var _loc10_ in param2) { if(!(_loc10_ == ""head"" && !param1.show_head_item)) { if(_loc10_ == ""chest"" && !param1.show_chest_item) { if(_loc4_ == ""f"" && param1.hasData(_loc10_,true)) { _loc5_ = _loc5_ + (getAppearanceShortForm(""bra_quality"") + "":"" + CItemTemplate.fromId(param1.getString(_loc10_)).quality + "";""); } } else if(!(_loc10_ == ""belt"" && !param1.show_belt_item)) { if(!(_loc10_ == ""legs"" && !param1.show_legs_item)) { if(!(_loc10_ == ""boots"" && !param1.show_boots_item)) { if(param1[_loc10_] != null) { _loc14_ = getAppearanceShortForm(_loc10_); _loc5_ = _loc5_ + (_loc14_ + "":"" + param1[_loc10_] + "";""); } } } } } } return _loc5_; } public static function compressMovieCoverSettings(param1:MovieCoverSettings, param2:Array) : String { var _loc9_:int = 0; var _loc14_:* = null; var _loc4_:String = param1.gender; var _loc5_:String = ""g:"" + _loc4_ + "";""; _loc5_ = _loc5_ + (""t:"" + param1.title + "";""); var _loc12_:* = 0; var _loc3_:Array = [""hair_type"",""hair_color"",""eyebrows_type"",""facial_hair_type"",""decoration_type""]; _loc9_ = 0; while(_loc9_ < _loc3_.length) { _loc12_ = _loc12_ | param1.getInt(_loc3_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""b:"" + _loc12_ + "";""); _loc12_ = 0; var _loc8_:Array = [""eyebrows_color"",""facial_hair_color""]; _loc9_ = 0; while(_loc9_ < _loc8_.length) { _loc12_ = _loc12_ | param1.getInt(_loc8_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""b2:"" + _loc12_ + "";""); _loc12_ = 0; var _loc11_:Array = [""skin_color"",""head_type"",""eyes_type"",""nose_type"",""mouth_type""]; _loc9_ = 0; while(_loc9_ < _loc11_.length) { _loc12_ = _loc12_ | param1.getInt(_loc11_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""s:"" + _loc12_ + "";""); _loc12_ = 0; var _loc13_:Array = [""tattoo_arm_left"",""tattoo_arm_right"",""tattoo_body"",""tattoo_leg_left"",""tattoo_leg_right""]; _loc9_ = 0; while(_loc9_ < _loc13_.length) { _loc12_ = _loc12_ | param1.getInt(_loc13_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""tt:"" + _loc12_ + "";""); _loc12_ = 0; var _loc6_:Array = [""bra_type"",""panties_type"",""genitals_type"",""genitals_hair_type"",""genitals_hair_color""]; _loc9_ = 0; while(_loc9_ < _loc6_.length) { _loc12_ = _loc12_ | param1.getInt(_loc6_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""uw:"" + _loc12_ + "";""); _loc12_ = 0; var _loc15_:Array = [""cover_rect_type"",""cover_border_type"",""cover_background_type"",""cover_layout_type"",""cover_actor_type""]; _loc9_ = 0; while(_loc9_ < _loc15_.length) { _loc12_ = _loc12_ | param1.getInt(_loc15_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""c:"" + _loc12_ + "";""); _loc12_ = 0; var _loc7_:Array = [""cover_filter_type"",""cover_layout_new_type"",""cover_font_type""]; _loc9_ = 0; while(_loc9_ < _loc7_.length) { _loc12_ = _loc12_ | param1.getInt(_loc7_[_loc9_]) << _loc9_ * 6; _loc9_++; } _loc5_ = _loc5_ + (""c2:"" + _loc12_ + "";""); var _loc17_:int = 0; var _loc16_:* = param2; for each(var _loc10_ in param2) { if(!(_loc10_ == ""head"" && !param1.show_head_item)) { if(_loc10_ == ""chest"" && !param1.show_chest_item) { if(_loc4_ == ""f"" && param1.hasData(_loc10_,true)) { _loc5_ = _loc5_ + (getAppearanceShortForm(""bra_quality"") + "":"" + CItemTemplate.fromId(param1.getString(_loc10_)).quality + "";""); } } else if(!(_loc10_ == ""belt"" && !param1.show_belt_item)) { if(!(_loc10_ == ""legs"" && !param1.show_legs_item)) { if(!(_loc10_ == ""boots"" && !param1.show_boots_item)) { if(param1.hasData(_loc10_,true)) { _loc14_ = getAppearanceShortForm(_loc10_); _loc5_ = _loc5_ + (_loc14_ + "":"" + param1.getData(_loc10_) + "";""); } } } } } } _loc5_ = _loc5_ + (""hba:"" + AppEnvironment.appPlatform.isHideBraAllowed + "";""); _loc5_ = _loc5_ + (""hpa:"" + AppEnvironment.appPlatform.isHidePantiesAllowed + "";""); return _loc5_; } private static function getAppearanceShortForm(param1:String) : String { var _loc2_:* = param1; switch(_loc2_) { case ""head"": return ""ih""; case ""chest"": return ""ic""; case ""legs"": return ""il""; case ""belt"": return ""ib""; case ""boots"": return ""ibo""; case ""bra_quality"": return ""bq""; default: return """"; } } public static function getMovieExtendTimeGameCurrengy(param1:int) : int { var _loc2_:int = CConstant.movie_extend_time_refill_cost_factor; var _loc3_:Number = _loc2_ * gameCurrencyPerTime(param1); return Math.round(_loc3_); } public static function getMovieExtendTimePremiumCurrengy(param1:int) : int { var _loc2_:* = 1; if(param1 <= CConstant.movie_extend_time_discount_1_max_level) { _loc2_ = Number(CConstant.movie_extend_time_premium_amount_discount_1); } else if(param1 <= CConstant.movie_extend_time_discount_2_max_level) { _loc2_ = Number(CConstant.movie_extend_time_premium_amount_discount_2); } else if(param1 <= CConstant.movie_extend_time_discount_3_max_level) { _loc2_ = Number(CConstant.movie_extend_time_premium_amount_discount_3); } var _loc3_:int = Math.round(CConstant.movie_extend_time_premium_amount * _loc2_); return _loc3_; } public static function getMovieExtendTimeDiscountMaxLevel(param1:int) : int { if(param1 <= CConstant.quest_energy_refill_discount_1_max_level) { return CConstant.quest_energy_refill_discount_1_max_level + 1; } if(param1 <= CConstant.quest_energy_refill_discount_2_max_level) { return CConstant.quest_energy_refill_discount_2_max_level + 1; } if(param1 <= CConstant.quest_energy_refill_discount_3_max_level) { return CConstant.quest_energy_refill_discount_3_max_level + 1; } return 0; } public static function getSenseBoosterDurationString(param1:int = -1) : String { if(param1 == -1) { param1 = CConstant.booster_sense_duration; } if(Environment.info.defaultLocale == ""pl_PL"") { return TimeUtil.secondsToString(param1); } return TimeUtil.getHourString(param1 / 3600); } public static function getDungeonUnlockFansCount(param1:String) : int { var _loc2_:CDungeonTemplate = CDungeonTemplate.fromId(param1); var _loc3_:CDungeonTemplateLevel = _loc2_.getLevel(1); return _loc3_.minFans; } public static function getDungeonPreviewImageUrl(param1:String) : String { return ServerInfo.assetURL(""dungeons/"" + param1 + ""_preview"",""png""); } public static function numMissionsInDungeon(param1:String) : int { var _loc2_:int = 0; var _loc5_:int = 0; var _loc4_:* = CDungeonQuestTemplate.ids; for each(var _loc3_ in CDungeonQuestTemplate.ids) { if(_loc3_.indexOf(param1) == 0) { _loc2_++; } } return _loc2_; } public static function getBattleSkillIconIdentifierFromBattleEffect(param1:int) : String { var _loc2_:int = BattleEffect.getBattleSkillId(param1); return CBattleSkill.fromId(_loc2_).identifier; } public static function calculateStatQuestWinChance(param1:Character, param2:int, param3:int, param4:Number = 0) : int { var _loc5_:* = null; var _loc11_:Array = [CConstant.quest_stat_base_easy,CConstant.quest_stat_base_medium,CConstant.quest_stat_base_hard]; var _loc10_:Number = _loc11_[param3 - 1]; var _loc12_:Number = CConstant.quest_stat_factor_increase; var _loc15_:int = 0; switch(int(param2) - 1) { case 0: _loc15_ = 2; break; case 1: _loc15_ = 3; break; case 2: _loc15_ = 4; break; case 3: _loc15_ = 5; } var _loc14_:Outfit = param1.outfits.getOutfitWithSetting(_loc15_); var _loc6_:Array = []; if(_loc14_) { _loc5_ = param1.outfits.getCharacterStatsWithOutfit(param1,_loc14_); _loc6_[1] = _loc5_.getInt(""stat_total_stamina""); _loc6_[2] = _loc5_.getInt(""stat_total_strength""); _loc6_[3] = _loc5_.getInt(""stat_total_critical_rating""); _loc6_[4] = _loc5_.getInt(""stat_total_dodge_rating""); } else { _loc6_[1] = param1.statTotalStamina; _loc6_[2] = param1.statTotalStrength; _loc6_[3] = param1.statTotalCriticalRating; _loc6_[4] = param1.statTotalDodgeRating; } var _loc8_:int = Math.round(CConstant.quest_stat_multiplier_1 * Math.pow(param1.level,2) + CConstant.quest_stat_multiplier_2 * param1.level); var _loc9_:int = Math.round(_loc8_ / 4); var _loc13_:int = _loc6_[param2]; var _loc7_:Number = _loc10_ + _loc13_ / _loc9_ * _loc12_; if(param4 > 0) { _loc7_ = _loc7_ - 10 * param4; } return Math.round(_loc7_ * 10); } public static function calculateNeededSatForStatQuest(param1:Character, param2:int, param3:int, param4:Number = 0) : int { var _loc8_:Array = [CConstant.quest_stat_base_easy,CConstant.quest_stat_base_medium,CConstant.quest_stat_base_hard]; var _loc7_:Number = _loc8_[param3 - 1]; var _loc5_:int = Math.round(CConstant.quest_stat_multiplier_1 * Math.pow(param1.level,2) + CConstant.quest_stat_multiplier_2 * param1.level); var _loc6_:int = Math.round(_loc5_ / 4); if(param4 > 0) { return Math.ceil(_loc6_ / 0.15 * (100 - _loc7_ + 10 * param4) / 100); } return Math.ceil(_loc6_ / 0.15 * (100 - _loc7_) / 100); } public static function getCharacterStages(param1:Character) : Vector. { var _loc3_:int = 0; var _loc2_:Vector. = new Vector.(0); _loc3_ = 1; while(_loc3_ <= param1.maxQuestStage) { _loc2_.push(_loc3_); _loc3_++; } _loc2_ = _loc2_.concat(getCustomStages(param1.level)); return _loc2_; } public static function getCustomStages(param1:int = -1) : Vector. { var _loc5_:* = null; var _loc3_:Vector. = new Vector.(0); var _loc4_:String = Environment.info.defaultLocale; var _loc7_:int = 0; var _loc6_:* = CCustomStage.ids; for each(var _loc2_ in CCustomStage.ids) { _loc5_ = CCustomStage.fromId(_loc2_); if((_loc5_.locales.indexOf(""all"") != -1 || _loc5_.locales.indexOf(_loc4_) != -1) && (param1 == -1 || param1 >= _loc5_.minLevel)) { _loc3_.push(_loc5_.stage); } } return _loc3_; } public static function isCustomStageUnlocked(param1:Character, param2:int) : Boolean { var _loc5_:* = null; var _loc4_:String = Environment.info.defaultLocale; var _loc7_:int = 0; var _loc6_:* = CCustomStage.ids; for each(var _loc3_ in CCustomStage.ids) { _loc5_ = CCustomStage.fromId(_loc3_); if(!(_loc5_.locales.indexOf(""all"") == -1 && _loc5_.locales.indexOf(_loc4_) == -1)) { if(_loc5_.stage == param2) { return param1.level >= _loc5_.minLevel; } } } return false; } public static function getHighestConventionRewardValue(param1:int) : int { var _loc3_:* = null; var _loc5_:int = 0; var _loc2_:* = 0; var _loc7_:int = 0; var _loc6_:* = CConventionReward.ids; for each(var _loc4_ in CConventionReward.ids) { _loc3_ = CConventionReward.fromId(_loc4_); _loc5_ = 0; switch(int(param1) - 1) { case 0: _loc5_ = _loc3_.reward1Value; break; case 1: _loc5_ = _loc3_.reward2Value; } if(_loc5_ > _loc2_) { _loc2_ = _loc5_; } } return _loc2_; } public static function getQuestStageUnlockLevel(param1:int) : int { var _loc3_:* = null; var _loc4_:* = null; if(param1 > CConstant.quest_max_stage) { _loc3_ = Environment.info.defaultLocale; var _loc6_:int = 0; var _loc5_:* = CCustomStage.ids; for each(var _loc2_ in CCustomStage.ids) { _loc4_ = CCustomStage.fromId(_loc2_); if(!(_loc4_.locales.indexOf(""all"") == -1 && _loc4_.locales.indexOf(_loc3_) == -1)) { if(_loc4_.stage == param1) { return _loc4_.minLevel; } } } } if(param1 == 2) { return 10; } if(param1 == 3) { return 30; } if(param1 == 4) { return 70; } if(param1 == 5) { return 110; } if(param1 == 6) { return 150; } if(param1 == 7) { return 200; } if(param1 == 8) { return 250; } if(param1 == 9) { return 300; } return 1; } public static function getEventQuestObjectiveRewardAmount(param1:int, param2:Number, param3:int) : int { var _loc10_:Number = NaN; var _loc8_:Number = NaN; var _loc11_:Number = NaN; var _loc6_:int = 0; var _loc5_:int = 0; var _loc7_:int = 0; var _loc9_:Number = NaN; var _loc4_:int = 0; switch(int(param1) - 1) { case 0: _loc10_ = gameCurrencyPerTime(param3); _loc8_ = CConstant.event_quest_objective_reward_game_currency_time; _loc11_ = CConstant.event_quest_objective_reward_game_currency_percentage_base; _loc11_ = _loc11_ * param2; _loc10_ = Math.round(_loc10_ * _loc11_ * _loc8_); _loc10_ = _loc10_ + Math.pow(param3,CConstant.event_quest_objective_reward_game_currency_exp); return Math.round(_loc10_); case 1: _loc4_ = CConstant.event_quest_objective_reward_premium_currency_base; _loc4_ = _loc4_ * Math.round(param2); return _loc4_; case 2: _loc4_ = CConstant.event_quest_objective_reward_stat_points_base; _loc4_ = _loc4_ * Math.round(param2); return _loc4_; case 3: if(param3 >= CConstant.max_level) { return 0; } _loc6_ = CLevel.fromId(param3).xp; _loc5_ = CLevel.fromId(param3 + 1).xp; _loc7_ = _loc5_ - _loc6_; _loc9_ = CConstant.event_quest_objective_reward_xp_percentage_base; _loc9_ = _loc9_ * param2; return Math.round(_loc7_ * _loc9_); } } public static function getOpticalChangeRewardAmount(param1:int, param2:Number) : int { var _loc3_:int = 0; switch(int(param1) - 1) { case 0: _loc3_ = CConstant.optical_changes_reward_stat_points_base; _loc3_ = _loc3_ * Math.round(param2); return _loc3_; case 1: return 0; case 2: _loc3_ = CConstant.optical_changes_reward_energy_base; _loc3_ = _loc3_ * Math.round(param2); return _loc3_; } } } } ",12240,True,2609.400253980084,median "package com.vizsage.as3mathlib.math.alg { /** * @class com.vizsage.as3mathlib.math.alg.Complex * @author Richard Wright * @version 1.7 * @description Implements the static behaviours of the Complex Class, with * algorithm logic based on the use of reverse Polish notation. *

* Supports all functions pertaining to the complex number calculator * and three added functions that are beyond the calculator's scope. * The calculator is capable of performing all basic operations: * powers, roots, logarithms, trigonometric functions, hyperbolic * functions, gamma and polygamma functions. Other than the following * exceptions, all methods call an inner 'Complex.input(re, im)' method * to capture the values of the two UI input fields for manipulation * within the outer method: *

 *              - new complex number instantiation (C button).
 *              - new Math.PI complex number instantiation (Pi button).
 *              - hold active complex number in memory (MR button).
 *              
* Although many of the methods are only used privately within the * class for the calculator's procedures, I have left all methods * declared as 'public static' to be able to utilize all class methods * in other application structures. * @usage
 *              var inst:Complex = new Complex(re, im);
 *              Complex.classMethod(args);
* @param re (Number) -- real portion of complex number from re_txt string * converted in UI. * @param im (Number) --imaginary portion of complex number from im_txt * string converted in UI. * ----------------------------------------------- * Latest update: August 8, 2004 * ----------------------------------------------- * AS2 revision copyright � 2003, Richard Wright [wisolutions2002@shaw.ca] * JS original copyright � 2003, Dario Alpern [http://www.alpertron.com.ar/ENGLISH.HTM] * ----------------------------------------------- * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of this software nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ----------------------------------------------- * Functions: * Complex(re, im) * 1. input(re, im) * 2. arg(x, y) * 3. chSign(c) * 4. norm(c) * 5. rAbs(c) * 6. abs(c) * 7. timesi(c) * 8. timesi3(c) * 9. adds(c1, c2) * 10. subt(c1, c2) * 11. mult(c1, c2) * 12. div(c1, c2) * 13. log(c) * 14. exp(c) * 15. sqrt(c) * 16. power(c1, c2) * 17. root(c1, c2) * 18. rSinh(r) * 19. rCosh(r) * 20. sin(c) * 21. cos(c) * 22. tan(c) * 23. cot(c) * 24. sec(c) * 25. cosec(c) * 26. asin(c) * 27. acos(c) * 28. atan(c) * 29. acot(c) * 30. asec(c) * 31. acosec(c) * 32. sinh(c) * 33. cosh(c) * 34. tanh(c) * 35. coth(c) * 36. sech(c) * 37. cosech(c) * 38. asinh(c) * 39. acosh(c) * 40. atanh(c) * 41. acoth(c) * 42. asech(c) * 43. acosech(c) * 44. contFrac(arguments) * 45. factorial(c) * 46. equals(c1, c2) * 47. conjugate(c) * 48. modulo(c) * 49. logGamma(c) * 50. diGamma(c) * 51. triGamma(c) * 52. tetraGamma(c) * 53. pentaGamma(c) * 54. hexaGamma(c) * - getters/setters * 55. get _real() * 55. set _real() * 56. get _imag() * 56. set _imag() * ----------------------------------------------- * Updates may be available at: * http://members.shaw.ca/flashprogramming/wisASLibrary/wis/ * ----------------------------------------------- **/ public class Complex { /** * @property $r (Number) -- real portion of complex number, any real number. * @property $i (Number) -- imaginary portion of complex number, any real number. * @property Mem (Complex) -- static -- holder for saved complex number. * @property One (Complex) -- static -- identity instantiated complex number. * @property Pi (Complex) -- static -- pi instantiated complex number. * @property ToRad (Complex) -- static -- (to radio group) rad-to-deg instantiated complex number for radio group manipulation. **/ private var $r:Number; private var $i:Number; public static var Mem:Complex = new Complex(0, 0); public static var One:Complex = new Complex(1, 0); public static var Pi:Complex = new Complex(Math.PI, 0); public static var ToRad:Complex = new Complex(180/Math.PI, 0); // constructor public function Complex(re:Number, im:Number) { //trace (""$$ Complex Class fired! $$""); $r = re; $i = im; } // 1. input -------------------------------------- /** * @method input * @description Main public method for capture of UI input from textfields to * instantiate a new Complex class instance. * @usage
Complex.input(re, im);
* @param re (Number) -- real portion of complex number from re_txt string converted in UI. * @param im (Number) -- imaginary portion of complex number from im_txt string converted in UI. * @return (Complex) -- returns a new Complex object. **/ public static function input(re:Number, im:Number):Complex { var oldRe:String = re.toString(); var oldIm:String = im.toString(); var newRe:String = """" var newIm:String = """"; var j:Number; for (j=0;jComplex.arg(x, y); * @param x (Number) -- any real number. * @param y (Number) -- any real number. * @return (Number) -- returns a real number based on input signs. **/ public static function arg(x:Number, y:Number):Number { if (x>0) return Math.atan(y/x); if (x<0 && y>=0) return Math.PI+Math.atan(y/x); if (x<0 && y<0) return -Math.PI+Math.atan(y/x); if (y>0) return Math.PI/2; if (y<0) return -Math.PI/2; return 0; } // 3. chSign ------------------------------------- /** * @method chSign * @description Method used within 'asinh' method and called with * 'chSign' button in UI. * @usage
Complex.chSign(c);
* @param c (Complex) -- 'log' of 'asinh' inner c2 complex number, or UI complex input. * @return (Complex) -- returns a modified Complex object. **/ public static function chSign(c:Complex):Complex { c.$r = -c.$r; c.$i = -c.$i; return c; } // 4. norm ---------------------------------------- /** * @method norm * @description Complex normal method used within 'atan', 'asinh', * and 'acosh' methods as a boolean construct. * @usage
Complex.norm(c);
* @param c (Complex) -- complex number to be normalized. * @return (Number) -- returns a real number. **/ public static function norm(c:Complex):Number { return(c.$r*c.$r+c.$i*c.$i); } // 5. rAbs --------------------------------------- /** * @method rAbs * @description Used within 'abs', 'log', and 'sqrt' methods. * @usage
Complex.rAbs(c);
* @param c (Complex) -- complex number input. * @return (Number) -- returns a positive real number. **/ public static function rAbs(c:Complex):Number { if (Math.abs(c.$r)>Math.abs(c.$i)) { return Math.abs(c.$r)*Math.sqrt(1+(c.$i/c.$r)*(c.$i/c.$r)); } return Math.abs(c.$i)*Math.sqrt(1+(c.$r/c.$i)*(c.$r/c.$i)); } // 6. abs ---------------------------------------- /** * @method abs * @description Method called by the UI abs button. * @usage
Complex.abs(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function abs(c:Complex):Complex { return new Complex(Complex.rAbs(c), 0); } // 7. timesi ------------------------------------- /** * @method timesi * @description Input is multiplied by i ... (sqrt(-1)). * @usage
Complex.timesi(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function timesi(c:Complex):Complex { return new Complex(-c.$i, c.$r); } // 8. timesi3 ------------------------------------ /** * @method timesi3 * @description Input is multiplied by i^3 ... (sqrt(-1)^3). * @usage
Complex.timesi3(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function timesi3(c:Complex):Complex { return new Complex(c.$i, -c.$r); } // 9. adds --------------------------------------- /** * @method adds * @description Adds two complex numbers. * @usage
Complex.adds(c1, c2);
* @param c1 (Complex) -- complex number input. * @param c2 (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function adds(c1:Complex, c2:Complex):Complex { return new Complex(c1.$r+c2.$r, c1.$i+c2.$i); } // 10. subt --------------------------------------- /** * @method subt * @description Subtracts two complex numbers. * @usage
Complex.subt(c1, c2);
* @param c1 (Complex) -- complex number input. * @param c2 (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function subt(c1:Complex, c2:Complex):Complex { return new Complex(c1.$r-c2.$r, c1.$i-c2.$i); } // 11. mult --------------------------------------- /** * @method mult * @description Multiplies two complex numbers. * @usage
Complex.mult(c1, c2);
* @param c1 (Complex) -- complex number input. * @param c2 (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function mult(c1:Complex, c2:Complex):Complex { return new Complex(c1.$r*c2.$r - c1.$i*c2.$i, c1.$i*c2.$r + c1.$r*c2.$i); } // 12. div ---------------------------------------- /** * @method div * @description Divides two complex numbers. * @usage
Complex.div(c1, c2);
* @param c1 (Complex) -- complex number input. * @param c2 (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function div(c1:Complex, c2:Complex):Complex { var r:Number; var s:Number; if (Math.abs(c2.$r)>=Math.abs(c2.$i)) { r = c2.$i/c2.$r; s = c2.$r+r*c2.$i; return new Complex((c1.$r+c1.$i*r)/s, (c1.$i-c1.$r*r)/s); } r = c2.$r/c2.$i; s = c2.$i+r*c2.$r; return new Complex((c1.$r*r+c1.$i)/s, (c1.$i*r-c1.$r)/s); } // 13. log ---------------------------------------- /** * @method log * @description Calculates the logarithm of the complex number. * @usage
Complex.log(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function log(c:Complex):Complex { return new Complex(Math.log(Complex.rAbs(c)), Complex.arg(c.$r, c.$i)); } // 14. exp ---------------------------------------- /** * @method exp * @description Calculates the product of the exponential number and * the complex number. * @usage
Complex.exp(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function exp(c:Complex):Complex { return new Complex(Math.exp(c.$r)*Math.cos(c.$i), Math.exp(c.$r)*Math.sin(c.$i)); } // 15. sqrt --------------------------------------- /** * @method sqrt * @description Calculates the squareroot of the complex number. * @usage
Complex.sqrt(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function sqrt(c:Complex):Complex { var aux:Number; if (c.$r>0) { aux = Complex.rAbs(c)+c.$r; return new Complex(Math.sqrt(aux/2), c.$i/Math.sqrt(2*aux)); } else { aux = Complex.rAbs(c)-c.$r; if (c.$i<0) { return new Complex(Math.abs(c.$i)/Math.sqrt(2*aux), -Math.sqrt(aux/2)); } else { return new Complex(Math.abs(c.$i)/Math.sqrt(2*aux), Math.sqrt(aux/2)); } } } // 16. power -------------------------------------- /** * @method power * @description Calculates c2 power of c1. * @usage
Complex.power(c1, c2);
* @param c1 (Complex) -- complex number input. * @param c2 (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function power(c1:Complex, c2:Complex):Complex { return Complex.exp(Complex.mult(Complex.log(c1), c2)); } // 17. root --------------------------------------- /** * @method root * @description Calculates c2 root of c1. * @usage
Complex.root(c1, c2);
* @param c1 (Complex) -- complex number input. * @param c2 (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function root(c1:Complex, c2:Complex):Complex { return Complex.exp(Complex.div(Complex.log(c1), c2)); } // 18. rSinh -------------------------------------- /** * @method rSinh * @description Calculates hyperbolic sine of real number input. * @usage
Complex.rSinh(r);
* @param r (Number) -- a real number. * @return (Number) -- returns a real number. **/ public static function rSinh(r:Number):Number { if (Math.abs(r)>.1) { return (Math.exp(r)-Math.exp(-r))/2; } else { var s:Number = 1; var j:Number; for (j=19;j>2;j-=2) s = s*r*r/j/(j-1)+1; return s*r; } } // 19. rCosh -------------------------------------- /** * @method rCosh * @description Calculates hyperbolic cosine of real number input. * @usage
Complex.rCosh(r);
* @param r (Number) -- a real number. * @return (Number) -- returns a real number. **/ public static function rCosh(r:Number):Number { return (Math.exp(r)+Math.exp(-r))/2; } // 20. sin ---------------------------------------- /** * @method sin * @description Calculates sine of complex number input. * @usage
Complex.sin(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function sin(c:Complex):Complex { return new Complex(Math.sin(c.$r)*Complex.rCosh(c.$i), Math.cos(c.$r)*Complex.rSinh(c.$i)); } // 21. cos ---------------------------------------- /** * @method cos * @description Calculates cosine of complex number input. * @usage
Complex.cos(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function cos(c:Complex):Complex { return new Complex(Math.cos(c.$r)*Complex.rCosh(c.$i), -Math.sin(c.$r)*Complex.rSinh(c.$i)); } // 22. tan ---------------------------------------- /** * @method tan * @description Calculates tangent of complex number input. * @usage
Complex.tan(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function tan(c:Complex):Complex { return Complex.div(Complex.sin(c), Complex.cos(c)); } // 23. cot ---------------------------------------- /** * @method cot * @description Calculates cotangent of complex number input. * @usage
Complex.cot(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function cot(c:Complex):Complex { return Complex.div(Complex.cos(c), Complex.sin(c)); } // 24. sec ---------------------------------------- /** * @method sec * @description Calculates secant of complex number input. * @usage
Complex.sec(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function sec(c:Complex):Complex { return Complex.div(Complex.One, Complex.cos(c)); } // 25. cosec -------------------------------------- /** * @method cosec * @description Calculates cosecant of complex number input. * @usage
Complex.cosec(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function cosec(c:Complex):Complex { return Complex.div(Complex.One, Complex.sin(c)); } // 26. asin --------------------------------------- /** * @method asin * @description Calculates arcsine of complex number input. * @usage
Complex.asin(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function asin(c:Complex):Complex { return Complex.timesi(Complex.asinh(Complex.timesi3(c))); } // 27. acos --------------------------------------- /** * @method acos * @description Calculates arccosine of complex number input. * @usage
Complex.acos(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function acos(c:Complex):Complex { return Complex.timesi(Complex.acosh(c)); } // 28. atan --------------------------------------- /** * @method atan * @description Calculates arctangent of complex number input. * @usage
Complex.atan(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function atan(c:Complex):Complex { var tre:Number = Complex.arg(1-Complex.norm(c), 2*c.$r)/2; var s:Number = 4*c.$i/(c.$r*c.$r+(c.$i-1)*(c.$i-1)); if (Math.abs(s)>.1) { return new Complex(tre, Math.log(1+s)/4); } else { var i2:Number = -1/20; var j:Number; s = -s; for (j=19;j>0;j--) i2 = i2*s-1/j; return new Complex(tre, s*i2/4) } } // 29. acot --------------------------------------- /** * @method acot * @description Calculates arccotangent of complex number input. * @usage
Complex.acot(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function acot(c:Complex):Complex { return Complex.atan(Complex.div(One, c)); } // 30. asec --------------------------------------- /** * @method asec * @description Calculates arcsecant of complex number input. * @usage
Complex.asec(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function asec(c:Complex):Complex { return Complex.timesi(Complex.asech(c)); } // 31. acosec ------------------------------------- /** * @method acosec * @description Calculates arccosecant of complex number input. * @usage
Complex.acosec(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function acosec(c:Complex):Complex { return Complex.asin(Complex.div(Complex.One, c)); } // 32. sinh --------------------------------------- /** * @method sinh * @description Calculates hyperbolic sine of complex number input. * @usage
Complex.sinh(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function sinh(c:Complex):Complex { return new Complex(Complex.rSinh(c.$r)*Math.cos(c.$i), Complex.rCosh(c.$r)*Math.sin(c.$i)); } // 33. cosh --------------------------------------- /** * @method cosh * @description Calculates hyperbolic cosine of complex number input. * @usage
Complex.cosh(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function cosh(c:Complex):Complex { return new Complex(Complex.rCosh(c.$r)*Math.cos(c.$i), Complex.rSinh(c.$r)*Math.sin(c.$i)); } // 34. tanh --------------------------------------- /** * @method tanh * @description Calculates hyperbolic tangent of complex number input. * @usage
Complex.tanh(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function tanh(c:Complex):Complex { return Complex.div(Complex.sinh(c), Complex.cosh(c)); } // 35. coth --------------------------------------- /** * @method coth * @description Calculates hyperbolic cotangent of complex number input. * @usage
Complex.coth(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function coth(c:Complex):Complex { return Complex.div(Complex.cosh(c), Complex.sinh(c)); } // 36. sech --------------------------------------- /** * @method sech * @description Calculates hyperbolic secant of complex number input. * @usage
Complex.sech(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function sech(c:Complex):Complex { return Complex.div(Complex.One, Complex.cosh(c)); } // 37. cosech ------------------------------------- /** * @method cosech * @description Calculates hyperbolic cosecant of complex number input. * @usage
Complex.cosech(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function cosech(c:Complex):Complex { return Complex.div(Complex.One, Complex.sinh(c)); } // 38. asinh -------------------------------------- /** * @method asinh * @description Calculates hyperbolic arcsine of complex number input. * @usage
Complex.asinh(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function asinh(c:Complex):Complex { var c1:Complex; var c2:Complex; var c3:Complex; var sgn:Number = 1; var j:Number; if (Complex.norm(c)>.1) { c1 = Complex.adds(Complex.sqrt(Complex.adds(Complex.mult(c, c), Complex.One)), c); c2 = Complex.subt(Complex.sqrt(Complex.adds(Complex.mult(c, c), Complex.One)), c); if (Complex.norm(c1) > Complex.norm(c2)) { return Complex.log(c1) } else { return Complex.chSign(Complex.log(c2)); } } else { c2 = new Complex(-1/19, 0); c3 = Complex.mult(c, c); for (j=17; j>0; j-=2) { c2 = Complex.mult(c3, c2); c2._real = (c2._real *j / (j+1)) + (sgn/j); c2._imag = (c2._imag *j / (j+1)); sgn = -sgn; } return Complex.mult(c, c2); } } // 39. acosh -------------------------------------- /** * @method acosh * @description Calculates hyperbolic arccosine of complex number input. * @usage
Complex.acosh(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function acosh(c:Complex):Complex { var c1:Complex = Complex.adds(Complex.sqrt(Complex.subt(Complex.mult(c, c), Complex.One)), c); var c2:Complex = Complex.subt(Complex.sqrt(Complex.subt(Complex.mult(c, c), Complex.One)), c); if (Complex.norm(c1)>Complex.norm(c2)) return Complex.log(c1); return Complex.log(Complex.mult(new Complex(-1, 0), c2)); } // 40. atanh -------------------------------------- /** * @method atanh * @description Calculates hyperbolic arctangent of complex number input. * @usage
Complex.atanh(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function atanh(c:Complex):Complex { return Complex.timesi(Complex.atan(Complex.timesi3(c))); } // 41. acoth -------------------------------------- /** * @method acoth * @description Calculates hyperbolic arccotangent of complex number input. * @usage
Complex.acoth(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function acoth(c:Complex):Complex { return Complex.atanh(Complex.div(Complex.One, c)); } // 42. asech -------------------------------------- /** * @method asech * @description Calculates hyperbolic arcsecant of complex number input. * @usage
Complex.asech(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function asech(c:Complex):Complex { return Complex.acosh(Complex.div(Complex.One, c)); } // 43. acosech ------------------------------------ /** * @method acosech * @description Calculates hyperbolic arccosecant of complex number input. * @usage
Complex.acosech(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function acosech(c:Complex):Complex { return Complex.asinh(Complex.div(Complex.One, c)); } // 44. contFrac ----------------------------------- /** * @method contFrac * @description Calculates continued fraction loop of complex number input * by applying variant fractional arguments. * @usage
Complex.contFrac(c);
* @param arguments (variant) -- 1st argument is complex number, balance are fractional input. * @return (Complex) -- returns a Complex object result. **/ public static function contFrac(...args):Complex { var s:Complex = Complex.div(new Complex(3, 0), args[0]); //, c); var j:Number; for (j=7;j>0;j--) { //s = Complex.div(new Complex(Complex.contFrac.arguments[j], 0), Complex.adds(c, s)); s = Complex.div(new Complex(args[j], 0), Complex.adds(args[0], s)); //(c, s)); trace(j+"" .. s._real: ""+s._real+"", _imag: ""+s._imag); } return s; } // 45. factorial ---------------------------------- /** * @method factorial * @description Calculates factorial of complex number input. * @usage
Complex.factorial(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function factorial(c:Complex):Complex { var c1:Complex; var c2:Complex; var s:Complex; var j:Number; if (c.$r<-1) { c2 = Complex.div(Complex.Pi, Complex.sin(Complex.mult(Complex.Pi, c))); c2.$r = -c2.$r; c2.$i = -c2.$i; c1 = Complex.subt(new Complex(5, 0), c); } else { c1 = Complex.adds(c, new Complex(6, 0)); } s = Complex.contFrac(c1, 1/12, 1/30, 53/210, 195/371, 22999/22737, 29944523/19733142, 109535241009/48264275462); s = Complex.adds(s, new Complex(.5*Math.log(2*Math.PI), 0)); s = Complex.adds(s, Complex.mult(Complex.adds(c1, new Complex(.5, 0)), Complex.log(c1))); s = Complex.exp(Complex.subt(s, c1)); for (j=0;j<6;j++) { s = Complex.div(s, c1); c1.$r--; } if (c.$r>=-1) return s; return Complex.div(c2, s); } // 46. equals ------------------------------------- /** * @method equals * @description Determines whether complex numbers c1 and c2 are equal. * @usage
Complex.equals(c1, c2);
* @param c1 (Complex) -- complex number input. * @param c2 (Complex) -- complex number input. * @return (Boolean) **/ public static function equals(c1:Complex, c2:Complex):Boolean { return (c1.$r==c2.$r && c1.$i==c2.$i); } // 47. conjugate ---------------------------------- /** * @method conjugate * @description Defines the conjugate of the complex number. * @usage
Complex.conjugate(c)
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a new Complex object. **/ public static function conjugate(c:Complex):Complex { return new Complex(c.$r, -c.$i); } // 48. modulo ------------------------------------- /** * @method modulo * @description Calculates the modulo of the complex number (length of vector). * @usage
Complex.modulo(c);
* @param c (Complex) -- complex number input. * @return (Number) -- returns a real number. **/ public static function modulo(c:Complex):Number { return Math.sqrt(c.$r*c.$r+c.$i*c.$i); } // 49. logGamma ----------------------------------- /** * @method logGamma * @description Calculates log Gamma of complex number input. * @usage
Complex.logGamma(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function logGamma(c:Complex):Complex { var c1:Complex; var c2:Complex; var s:Complex; var j:Number; if (c.$r<0) { c2 = Complex.log(Complex.sin(Complex.mult(Complex.Pi, c))); c1 = Complex.subt(new Complex(6, 0), c); trace (""1. Complex.logGamma (c.$r<0) ... c2.$r: ""+c2.$r+"", $i: ""+c2.$i+"", c1.$r: ""+c1.$r+"", $i: ""+c1.$i); } else { c1 = Complex.adds(c, new Complex(7, 0)); trace (""2. Complex.logGamma (c.$r>=0) ... c1.$r: ""+c1.$r+"", $i: ""+c1.$i); } s = Complex.contFrac(c1, 1/12, 1/30, 53/210, 195/371, 22999/22737, 29944523/19733142, 109535241009/48264275462); trace (""3. Complex.logGamma contFrac ... s.$r: ""+s.$r+"", $i: ""+s.$i); s = Complex.adds(s, new Complex(.5*Math.log(2*Math.PI), 0)); trace (""4. Complex.logGamma adds ... s.$r: ""+s.$r+"", $i: ""+s.$i); s = Complex.subt(Complex.adds(s, Complex.mult(Complex.subt(c1, new Complex(.5, 0)), Complex.log(c1))), c1); trace (""5. Complex.logGamma subt ... s.$r: ""+s.$r+"", $i: ""+s.$i); for (j=0;j<7;j++) { c1.$r--; s = Complex.subt(s, Complex.log(c1)); trace (""6. Complex.logGamma subt ""+j+"" ... s.$r: ""+s.$r+"", $i: ""+s.$i); } trace (""7. Complex.logGamma (c.$r>=0): ""+(c.$r>=0)+"" ... s.$r: ""+s.$r+"", $i: ""+s.$i); if (c.$r>=0) return s; trace (""8. Complex.logGamma return: ""+(c.$r<0)+"" ... s.$r: ""+s.$r+"", $i: ""+s.$i+"", c2.$r: ""+c2.$r+"", $i: ""+c2.$i); return Complex.subt(s, c2); } // 50. diGamma ------------------------------------ /** * @method diGamma * @description Calculates power2 Gamma of complex number input. * @usage
Complex.diGamma(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function diGamma(c:Complex):Complex { var c1:Complex; var c2:Complex; var s:Complex; var j:Number; if (c.$r<0) { c2 = Complex.div(Complex.Pi, Complex.tan(Complex.mult(Complex.Pi, c))); c1 = Complex.subt(new Complex(6, 0), c); } else { c1 = Complex.adds(c, new Complex(7, 0)); } s = Complex.contFrac(c1, 1/12, 1/10, 79/210, 1205/1659, 262445/209429, 33461119209/18089284070, 361969913862291/137627660760070); s = Complex.div(s, c1); s = Complex.adds(s, Complex.div(new Complex(.5, 0), c1)); s = Complex.subt(Complex.log(c1), s); for (j=0;j<7;j++) { c1.$r--; s = Complex.subt(s, Complex.div(Complex.One, c1)); } if (c.$r>=0) return s; return Complex.subt(s, c2); } // 51. triGamma ----------------------------------- /** * @method triGamma * @description Calculates power3 Gamma of complex number input. * @usage
Complex.triGamma(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function triGamma(c:Complex):Complex { var c1:Complex; var c2:Complex; var c3:Complex; var u:Complex; var s:Complex; var j:Number; if (c.$r<0) { u = Complex.cot(Complex.mult(Complex.Pi, c)); c2 = Complex.mult(Complex.mult(Complex.Pi, Complex.Pi), Complex.adds(Complex.mult(u, u), Complex.One)); c1 = Complex.subt(new Complex(6, 0), c); } else { c1 = Complex.adds(c, new Complex(7, 0)); } s = Complex.contFrac(c1, 1/6, 1/5, 18/35, 20/21, 50/33, 315/143, 196/65); s = Complex.adds(s, new Complex(.5, 0)); s = Complex.div(s, c1); s = Complex.adds(s, Complex.One); s = Complex.div(s, c1); for (j=0;j<7;j++) { c1.$r--; c3 = Complex.mult(c1, c1); s = Complex.adds(s, Complex.div(Complex.One, c3)); } if (c.$r>=0) return s; return Complex.subt(c2, s); } // 52. tetraGamma --------------------------------- /** * @method tetraGamma * @description Calculates power4 Gamma of complex number input. * @usage
Complex.tetraGamma(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function tetraGamma(c:Complex):Complex { var c1:Complex; var c2:Complex; var c3:Complex; var u:Complex; var s:Complex; var j:Number; if (c.$r<0) { u = Complex.cot(Complex.mult(Complex.Pi, c)); c2 = Complex.mult(new Complex(2*Math.PI*Math.PI*Math.PI, 0), Complex.mult(u, Complex.adds(Complex.mult(u, u), Complex.One))); c1 = Complex.subt(new Complex(6, 0), c); } else { c1 = Complex.adds(c, new Complex(7, 0)); } s = Complex.contFrac(c1, 1/2, 1/3, 2/3, 6/5, 9/5, 18/7, 24/7); s = Complex.div(Complex.div(Complex.adds(Complex.div(Complex.adds(s, Complex.One), c1), Complex.One), c1), c1); s.$r = -s.$r; s.$i = -s.$i; for (j=0;j<7;j++) { c1.$r--; c3 = Complex.mult(Complex.mult(c1, c1), c1); c3.$r /= 2; c3.$i /= 2; s = Complex.subt(s, Complex.div(Complex.One, c3)); } if (c.$r>=0) return s; return Complex.subt(s, c2); } // 53. pentaGamma --------------------------------- /** * @method pentaGamma * @description Calculates power5 Gamma of complex number input. * @usage
Complex.pentaGamma(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function pentaGamma(c:Complex):Complex { var c1:Complex; var c2:Complex; var c3:Complex; var u:Complex; var s:Complex; var j:Number; /* if (c.$r<0) { u = Complex.cot(Complex.mult(Complex.Pi, c)); c2 = Complex.adds( Complex.mult( Complex.adds( Complex.mult( Complex.mult(u, u), Complex.mult( new Complex(6, 0) ), new Complex(8, 0) ), Complex.mult(u, u)), new Complex(2, 0)) ); c2.$r *= -Math.PI*Math.PI*Math.PI*Math.PI; c2.$i *= -Math.PI*Math.PI*Math.PI*Math.PI; c1 = Complex.subt(new Complex(6, 0), c); } else { c1 = Complex.adds(c, new Complex(7, 0)); } s = Complex.contFrac(c1, 2, 1/2, 5/6, 22/15, 116/55, 942/319, 17622/4553); s = Complex.div(Complex.div(Complex.div(Complex.adds(Complex.div(Complex.adds(s, new Complex(3, 0)), c1), new Complex(2, 0)), c1), c1), c1); for (j=0;j<7;j++) { c1.$r--; var c3 = Complex.mult(Complex.mult(c1, c1), Complex.mult(c1, c1)); c3.$r /= 6; c3.$i /= 6; s = Complex.adds(s, Complex.div(Complex.One, c3)); } if (c.$r>=0) return s; return Complex.subt(c2, s);*/ throw new Error(""This needs to be reimplemented""); } // 54. hexaGamma ---------------------------------- /** * @method hexaGamma * @description Calculates power6 Gamma of complex number input. * @usage
Complex.hexaGamma(c);
* @param c (Complex) -- complex number input. * @return (Complex) -- returns a Complex object result. **/ public static function hexaGamma(c:Complex):Complex { /* var c1:Complex; var c2:Complex; var c3:Complex; var u:Complex; var s:Complex; var j:Number; if (c.$r<0) { u = Complex.cot(Complex.mult(Complex.Pi, c)); c2 = Complex.mult(Complex.adds(Complex.mult(Complex.adds(Complex.mult(Complex.mult(u, u), Complex.mult(new Complex(24, 0)), new Complex(40, 0)), Complex.mult(u, u)), new Complex(16, 0)), u)); c2.$r *= -Math.PI*Math.PI*Math.PI*Math.PI*Math.PI; c2.$i *= -Math.PI*Math.PI*Math.PI*Math.PI*Math.PI; c1 = subt(new Complex(6, 0), c); } else { c1 = adds(c, new Complex(7, 0)); } s = Complex.contFrac(c1, 10, 7/10, 71/70, 870/497, 15092/6177, 156910/46893, 2585118/595595); s = Complex.div(Complex.div(Complex.div(Complex.div(Complex.adds(Complex.div(Complex.adds(s, new Complex(12, 0)), c1), new Complex(6, 0)), c1), c1), c1), c1); s.$r = -s.$r; s.$i = -s.$i; for (j=0;j<7;j++) { c1.$r--; c3 = Complex.mult(Complex.mult(Complex.mult(c1, c1), Complex.mult(c1, c1)), c1); c3.$r /= 24; c3.$i /= 24; s = Complex.subt(s, Complex.div(Complex.One, c3)); } if (c.$r>=0) return s; return Complex.subt(s, c2); */ throw new Error(""This needs to be reimplemented""); } // 55. get _real ---------------------------------- /** * @method get _real * @description Gets real portion of Complex object. * @usage
Complex._real;
* @return (Number) -- returns a real number. **/ public function get _real():Number { return $r; } // 56. set _real ---------------------------------- /** * @method set _real * @description Sets real portion of Complex object. * @usage
Complex._real = num;
* @param (Number) -- a real number. * @return (void) **/ public function set _real(num:Number):void { $r = num; } // 57. get _imag ---------------------------------- /** * @method get _imag * @description Gets imaginary portion of Complex object. * @usage
Complex._imag);
* @return (Number) -- returns a real number (to be multiplied by i). **/ public function get _imag():Number { return $i; } // 58. set _imag ---------------------------------- /** * @method get _imag * @description Sets imaginary portion of Complex object. * @usage
Complex._imag = num;
* @return (void) **/ public function set _imag(num:Number):void { $i = num; } }// class }//package ",12343,True,2594.8616617885878,median "{-# OPTIONS --without-K --exact-split --allow-unsolved-metas #-} module 15-number-theory where import 14-image open 14-image public -- Section 10.1 Decidability. {- Recall that a proposition P is decidable if P + (¬ P) holds. -} classical-Prop : (l : Level) → UU (lsuc l) classical-Prop l = Σ (UU-Prop l) (λ P → is-decidable (pr1 P)) is-decidable-Eq-ℕ : (m n : ℕ) → is-decidable (Eq-ℕ m n) is-decidable-Eq-ℕ zero-ℕ zero-ℕ = inl star is-decidable-Eq-ℕ zero-ℕ (succ-ℕ n) = inr id is-decidable-Eq-ℕ (succ-ℕ m) zero-ℕ = inr id is-decidable-Eq-ℕ (succ-ℕ m) (succ-ℕ n) = is-decidable-Eq-ℕ m n is-decidable-leq-ℕ : (m n : ℕ) → is-decidable (leq-ℕ m n) is-decidable-leq-ℕ zero-ℕ zero-ℕ = inl star is-decidable-leq-ℕ zero-ℕ (succ-ℕ n) = inl star is-decidable-leq-ℕ (succ-ℕ m) zero-ℕ = inr id is-decidable-leq-ℕ (succ-ℕ m) (succ-ℕ n) = is-decidable-leq-ℕ m n is-decidable-le-ℕ : (m n : ℕ) → is-decidable (le-ℕ m n) is-decidable-le-ℕ zero-ℕ zero-ℕ = inr id is-decidable-le-ℕ zero-ℕ (succ-ℕ n) = inl star is-decidable-le-ℕ (succ-ℕ m) zero-ℕ = inr id is-decidable-le-ℕ (succ-ℕ m) (succ-ℕ n) = is-decidable-le-ℕ m n {- We say that a type has decidable equality if we can decide whether x = y holds for any x,y:A. -} has-decidable-equality : {l : Level} (A : UU l) → UU l has-decidable-equality A = (x y : A) → is-decidable (Id x y) {- The type ℕ is an example of a type with decidable equality. -} Eq-ℕ-eq : (x y : ℕ) → Id x y → Eq-ℕ x y Eq-ℕ-eq x .x refl = refl-Eq-ℕ x is-injective-succ-ℕ : (x y : ℕ) → Id (succ-ℕ x) (succ-ℕ y) → Id x y is-injective-succ-ℕ zero-ℕ zero-ℕ p = refl is-injective-succ-ℕ zero-ℕ (succ-ℕ y) p = ind-empty { P = λ t → Id zero-ℕ (succ-ℕ y)} ( Eq-ℕ-eq one-ℕ (succ-ℕ (succ-ℕ y)) p) is-injective-succ-ℕ (succ-ℕ x) zero-ℕ p = ind-empty { P = λ t → Id (succ-ℕ x) zero-ℕ} ( Eq-ℕ-eq (succ-ℕ (succ-ℕ x)) one-ℕ p) is-injective-succ-ℕ (succ-ℕ x) (succ-ℕ y) p = ap succ-ℕ (eq-Eq-ℕ x y (Eq-ℕ-eq (succ-ℕ (succ-ℕ x)) (succ-ℕ (succ-ℕ y)) p)) has-decidable-equality-ℕ : has-decidable-equality ℕ has-decidable-equality-ℕ zero-ℕ zero-ℕ = inl refl has-decidable-equality-ℕ zero-ℕ (succ-ℕ y) = inr (Eq-ℕ-eq zero-ℕ (succ-ℕ y)) has-decidable-equality-ℕ (succ-ℕ x) zero-ℕ = inr (Eq-ℕ-eq (succ-ℕ x) zero-ℕ) has-decidable-equality-ℕ (succ-ℕ x) (succ-ℕ y) = functor-coprod ( ap succ-ℕ) ( λ (f : ¬ (Id x y)) p → f (is-injective-succ-ℕ x y p)) ( has-decidable-equality-ℕ x y) {- Types with decidable equality are closed under coproducts. -} has-decidable-equality-coprod : {l1 l2 : Level} {A : UU l1} {B : UU l2} → has-decidable-equality A → has-decidable-equality B → has-decidable-equality (coprod A B) has-decidable-equality-coprod dec-A dec-B (inl x) (inl y) = functor-coprod ( ap inl) ( λ f p → f (inv-is-equiv (is-emb-inl _ _ x y) p)) ( dec-A x y) has-decidable-equality-coprod {A = A} {B = B} dec-A dec-B (inl x) (inr y) = inr ( λ p → inv-is-equiv ( is-equiv-map-raise _ empty) ( Eq-coprod-eq A B (inl x) (inr y) p)) has-decidable-equality-coprod {A = A} {B = B} dec-A dec-B (inr x) (inl y) = inr ( λ p → inv-is-equiv ( is-equiv-map-raise _ empty) ( Eq-coprod-eq A B (inr x) (inl y) p)) has-decidable-equality-coprod dec-A dec-B (inr x) (inr y) = functor-coprod ( ap inr) ( λ f p → f (inv-is-equiv (is-emb-inr _ _ x y) p)) ( dec-B x y) {- Decidable equality of Fin n. -} has-decidable-equality-empty : has-decidable-equality empty has-decidable-equality-empty () has-decidable-equality-unit : has-decidable-equality unit has-decidable-equality-unit star star = inl refl has-decidable-equality-Fin : (n : ℕ) → has-decidable-equality (Fin n) has-decidable-equality-Fin zero-ℕ = has-decidable-equality-empty has-decidable-equality-Fin (succ-ℕ n) = has-decidable-equality-coprod ( has-decidable-equality-Fin n) ( has-decidable-equality-unit) decidable-Eq-Fin : (n : ℕ) (i j : Fin n) → classical-Prop lzero decidable-Eq-Fin n i j = pair ( pair (Id i j) (is-set-Fin n i j)) ( has-decidable-equality-Fin n i j) {- Decidable equality of ℤ. -} has-decidable-equality-ℤ : has-decidable-equality ℤ has-decidable-equality-ℤ = has-decidable-equality-coprod has-decidable-equality-ℕ ( has-decidable-equality-coprod has-decidable-equality-unit has-decidable-equality-ℕ) {- Next, we show that types with decidable equality are sets. To see this, we will construct a fiberwise equivalence with the binary relation R that is defined by R x y := unit if (x = y), and empty otherwise. In order to define this relation, we first define a type family over ((x = y) + ¬(x = y)) that returns unit on the left and empty on the right. -} splitting-decidable-equality : {l : Level} (A : UU l) (x y : A) → is-decidable (Id x y) → UU lzero splitting-decidable-equality A x y (inl p) = unit splitting-decidable-equality A x y (inr f) = empty is-prop-splitting-decidable-equality : {l : Level} (A : UU l) (x y : A) → (t : is-decidable (Id x y)) → is-prop (splitting-decidable-equality A x y t) is-prop-splitting-decidable-equality A x y (inl p) = is-prop-unit is-prop-splitting-decidable-equality A x y (inr f) = is-prop-empty reflexive-splitting-decidable-equality : {l : Level} (A : UU l) (x : A) → (t : is-decidable (Id x x)) → splitting-decidable-equality A x x t reflexive-splitting-decidable-equality A x (inl p) = star reflexive-splitting-decidable-equality A x (inr f) = ind-empty {P = λ t → splitting-decidable-equality A x x (inr f)} (f refl) eq-splitting-decidable-equality : {l : Level} (A : UU l) (x y : A) → (t : is-decidable (Id x y)) → splitting-decidable-equality A x y t → Id x y eq-splitting-decidable-equality A x y (inl p) t = p eq-splitting-decidable-equality A x y (inr f) t = ind-empty {P = λ s → Id x y} t is-set-has-decidable-equality : {l : Level} (A : UU l) → has-decidable-equality A → is-set A is-set-has-decidable-equality A d = is-set-prop-in-id ( λ x y → splitting-decidable-equality A x y (d x y)) ( λ x y → is-prop-splitting-decidable-equality A x y (d x y)) ( λ x → reflexive-splitting-decidable-equality A x (d x x)) ( λ x y → eq-splitting-decidable-equality A x y (d x y)) {- Closure of decidable types under retracts and equivalences. -} is-decidable-retract-of : {l1 l2 : Level} {A : UU l1} {B : UU l2} → A retract-of B → is-decidable B → is-decidable A is-decidable-retract-of (pair i (pair r H)) (inl b) = inl (r b) is-decidable-retract-of (pair i (pair r H)) (inr f) = inr (f ∘ i) is-decidable-is-equiv : {l1 l2 : Level} {A : UU l1} {B : UU l2} {f : A → B} (is-equiv-f : is-equiv f) → is-decidable B → is-decidable A is-decidable-is-equiv {f = f} (pair (pair g G) (pair h H)) = is-decidable-retract-of (pair f (pair h H)) is-decidable-equiv : {l1 l2 : Level} {A : UU l1} {B : UU l2} (e : A ≃ B) → is-decidable B → is-decidable A is-decidable-equiv e = is-decidable-is-equiv (is-equiv-map-equiv e) is-decidable-equiv' : {l1 l2 : Level} {A : UU l1} {B : UU l2} (e : A ≃ B) → is-decidable A → is-decidable B is-decidable-equiv' e = is-decidable-equiv (inv-equiv e) has-decidable-equality-retract-of : {l1 l2 : Level} {A : UU l1} {B : UU l2} → A retract-of B → has-decidable-equality B → has-decidable-equality A has-decidable-equality-retract-of (pair i (pair r H)) d x y = is-decidable-retract-of ( Id-retract-of-Id (pair i (pair r H)) x y) ( d (i x) (i y)) {- The well-ordering principle. -} is-minimal-element-ℕ : {l : Level} (P : ℕ → UU l) (n : ℕ) (p : P n) → UU l is-minimal-element-ℕ P n p = (m : ℕ) → P m → (leq-ℕ n m) minimal-element-ℕ : {l : Level} (P : ℕ → UU l) → UU l minimal-element-ℕ P = Σ ℕ (λ n → Σ (P n) (is-minimal-element-ℕ P n)) is-minimal-element-succ-ℕ : {l : Level} (P : ℕ → UU l) (d : (n : ℕ) → is-decidable (P n)) (m : ℕ) (pm : P (succ-ℕ m)) (is-min-m : is-minimal-element-ℕ (λ x → P (succ-ℕ x)) m pm) → ¬ (P zero-ℕ) → is-minimal-element-ℕ P (succ-ℕ m) pm is-minimal-element-succ-ℕ P d m pm is-min-m neg-p0 zero-ℕ p0 = ind-empty (neg-p0 p0) is-minimal-element-succ-ℕ P d zero-ℕ pm is-min-m neg-p0 (succ-ℕ n) psuccn = leq-zero-ℕ n is-minimal-element-succ-ℕ P d (succ-ℕ m) pm is-min-m neg-p0 (succ-ℕ n) psuccn = is-minimal-element-succ-ℕ (λ x → P (succ-ℕ x)) (λ x → d (succ-ℕ x)) m pm ( λ m → is-min-m (succ-ℕ m)) ( is-min-m zero-ℕ) ( n) ( psuccn) well-ordering-principle-succ-ℕ : {l : Level} (P : ℕ → UU l) (d : (n : ℕ) → is-decidable (P n)) (n : ℕ) (p : P (succ-ℕ n)) → is-decidable (P zero-ℕ) → minimal-element-ℕ (λ m → P (succ-ℕ m)) → minimal-element-ℕ P well-ordering-principle-succ-ℕ P d n p (inl p0) _ = pair zero-ℕ (pair p0 (λ m q → leq-zero-ℕ m)) well-ordering-principle-succ-ℕ P d n p (inr neg-p0) (pair m (pair pm is-min-m)) = pair ( succ-ℕ m) ( pair pm ( is-minimal-element-succ-ℕ P d m pm is-min-m neg-p0)) well-ordering-principle-ℕ : {l : Level} (P : ℕ → UU l) (d : (n : ℕ) → is-decidable (P n)) → Σ ℕ P → minimal-element-ℕ P well-ordering-principle-ℕ P d (pair zero-ℕ p) = pair zero-ℕ (pair p (λ m q → leq-zero-ℕ m)) well-ordering-principle-ℕ P d (pair (succ-ℕ n) p) = well-ordering-principle-succ-ℕ P d n p (d zero-ℕ) ( well-ordering-principle-ℕ ( λ m → P (succ-ℕ m)) ( λ m → d (succ-ℕ m)) ( pair n p)) -- Exercise 6.7 -- We prove that the induction principle for ℕ implies strong induction. -- We first prove some lemmas about inequality. zero-ℕ-leq-ℕ : (n : ℕ) → leq-ℕ zero-ℕ n zero-ℕ-leq-ℕ n = star is-prop-leq-ℕ : (m n : ℕ) → is-prop (leq-ℕ m n) is-prop-leq-ℕ zero-ℕ zero-ℕ = is-prop-unit is-prop-leq-ℕ zero-ℕ (succ-ℕ n) = is-prop-unit is-prop-leq-ℕ (succ-ℕ m) zero-ℕ = is-prop-empty is-prop-leq-ℕ (succ-ℕ m) (succ-ℕ n) = is-prop-leq-ℕ m n neg-succ-leq-ℕ : (n : ℕ) → ¬ (leq-ℕ (succ-ℕ n) n) neg-succ-leq-ℕ zero-ℕ = id neg-succ-leq-ℕ (succ-ℕ n) = neg-succ-leq-ℕ n leq-eq-left-ℕ : {m m' : ℕ} → Id m m' → (n : ℕ) → leq-ℕ m n → leq-ℕ m' n leq-eq-left-ℕ refl n = id leq-eq-right-ℕ : (m : ℕ) {n n' : ℕ} → Id n n' → leq-ℕ m n → leq-ℕ m n' leq-eq-right-ℕ m refl = id cases-leq-succ-ℕ : {m n : ℕ} → leq-ℕ m (succ-ℕ n) → coprod (leq-ℕ m n) (Id m (succ-ℕ n)) cases-leq-succ-ℕ {zero-ℕ} {n} star = inl star cases-leq-succ-ℕ {succ-ℕ m} {zero-ℕ} p = inr (ap succ-ℕ (anti-symmetric-leq-ℕ m zero-ℕ p star)) cases-leq-succ-ℕ {succ-ℕ m} {succ-ℕ n} p = functor-coprod id (ap succ-ℕ) (cases-leq-succ-ℕ p) -- Now we begin with the proof of the theorem fam-strong-ind-ℕ : { l : Level} → (ℕ → UU l) → ℕ → UU l fam-strong-ind-ℕ P n = (m : ℕ) → (leq-ℕ m n) → P m zero-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → P zero-ℕ → fam-strong-ind-ℕ P zero-ℕ zero-strong-ind-ℕ P p0 zero-ℕ t = p0 zero-strong-ind-ℕ P p0 (succ-ℕ m) () eq-zero-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) (p0 : P zero-ℕ) (t : leq-ℕ zero-ℕ zero-ℕ) → Id (zero-strong-ind-ℕ P p0 zero-ℕ t) p0 eq-zero-strong-ind-ℕ P p0 t = refl cases-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) → (fam-strong-ind-ℕ P k) → ( m : ℕ) ( c : coprod (leq-ℕ m k) (Id m (succ-ℕ k))) → P m cases-succ-strong-ind-ℕ P pS k H m (inl q) = H m q cases-succ-strong-ind-ℕ P pS k H .(succ-ℕ k) (inr refl) = pS k H succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) → (fam-strong-ind-ℕ P k) → (fam-strong-ind-ℕ P (succ-ℕ k)) succ-strong-ind-ℕ P pS k H m p = cases-succ-strong-ind-ℕ P pS k H m (cases-leq-succ-ℕ p) cases-type-htpy-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) (H : fam-strong-ind-ℕ P k) (m : ℕ) ( c : coprod (leq-ℕ m k) (Id m (succ-ℕ k))) → UU l cases-type-htpy-succ-strong-ind-ℕ P pS k H m (inl q) = Id ( cases-succ-strong-ind-ℕ P pS k H m (inl q)) ( H m q) cases-type-htpy-succ-strong-ind-ℕ P pS k H m (inr α) = Id ( cases-succ-strong-ind-ℕ P pS k H (succ-ℕ k) (inr refl)) ( pS k H) type-htpy-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) (H : fam-strong-ind-ℕ P k) (m : ℕ) ( p : leq-ℕ m (succ-ℕ k)) → UU l type-htpy-succ-strong-ind-ℕ P pS k H m p = cases-type-htpy-succ-strong-ind-ℕ P pS k H m (cases-leq-succ-ℕ p) {- cases-htpy-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) (H : fam-strong-ind-ℕ P k) (m : ℕ) → ( c : coprod (leq-ℕ m k) (Id m (succ-ℕ k))) → cases-type-htpy-succ-strong-ind-ℕ P pS k H m c cases-htpy-succ-strong-ind-ℕ P pS k H m (inl q) = refl cases-htpy-succ-strong-ind-ℕ P pS k H .(succ-ℕ k) (inr refl) = refl htpy-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) (H : fam-strong-ind-ℕ P k) (m : ℕ) (p : leq-ℕ m (succ-ℕ k)) → type-htpy-succ-strong-ind-ℕ P pS k H m p htpy-succ-strong-ind-ℕ P pS k H m p = cases-htpy-succ-strong-ind-ℕ P pS k H m (cases-leq-succ-ℕ p) -} cases-htpy-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) (H : fam-strong-ind-ℕ P k) (m : ℕ) ( c : coprod (leq-ℕ m k) (Id m (succ-ℕ k))) → ( q : leq-ℕ m k) → Id ( cases-succ-strong-ind-ℕ P pS k H m c) ( H m q) cases-htpy-succ-strong-ind-ℕ P pS k H m (inl p) q = ap (H m) (is-prop'-is-prop (is-prop-leq-ℕ m k) p q) cases-htpy-succ-strong-ind-ℕ P pS k H m (inr α) q = ex-falso' ( neg-succ-leq-ℕ k (leq-eq-left-ℕ α k q)) htpy-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) (H : fam-strong-ind-ℕ P k) (m : ℕ) ( p : leq-ℕ m (succ-ℕ k)) → ( q : leq-ℕ m k) → Id ( succ-strong-ind-ℕ P pS k H m p) ( H m q) htpy-succ-strong-ind-ℕ P pS k H m p q = cases-htpy-succ-strong-ind-ℕ P pS k H m (cases-leq-succ-ℕ p) q cases-eq-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) (H : fam-strong-ind-ℕ P k) ( c : coprod (leq-ℕ (succ-ℕ k) k) (Id (succ-ℕ k) (succ-ℕ k))) → ( q : Id (succ-ℕ k) (succ-ℕ k)) → Id ( (cases-succ-strong-ind-ℕ P pS k H (succ-ℕ k) c)) ( pS k H) cases-eq-succ-strong-ind-ℕ P pS k H (inl p) q = ex-falso' (neg-succ-leq-ℕ k p) cases-eq-succ-strong-ind-ℕ P pS k H (inr α) q = ap ( (cases-succ-strong-ind-ℕ P pS k H (succ-ℕ k)) ∘ inr) ( is-prop'-is-prop (is-set-ℕ (succ-ℕ k) (succ-ℕ k)) α refl) eq-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( k : ℕ) (H : fam-strong-ind-ℕ P k) ( p : leq-ℕ (succ-ℕ k) (succ-ℕ k)) (q : Id (succ-ℕ k) (succ-ℕ k)) → Id ( (succ-strong-ind-ℕ P pS k H (succ-ℕ k) p)) ( pS k H) eq-succ-strong-ind-ℕ P pS k H p q = cases-eq-succ-strong-ind-ℕ P pS k H (cases-leq-succ-ℕ p) q conclusion-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( ( n : ℕ) → fam-strong-ind-ℕ P n) → (n : ℕ) → P n conclusion-strong-ind-ℕ P f n = f n n (reflexive-leq-ℕ n) induction-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( fam-strong-ind-ℕ P zero-ℕ) → ( (k : ℕ) → (fam-strong-ind-ℕ P k) → (fam-strong-ind-ℕ P (succ-ℕ k))) → ( n : ℕ) → fam-strong-ind-ℕ P n induction-strong-ind-ℕ P q0 qS zero-ℕ = q0 induction-strong-ind-ℕ P q0 qS (succ-ℕ n) = qS n ( induction-strong-ind-ℕ P q0 qS n) strong-ind-ℕ : { l : Level} → (P : ℕ → UU l) (p0 : P zero-ℕ) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( n : ℕ) → P n strong-ind-ℕ P p0 pS = conclusion-strong-ind-ℕ P ( induction-strong-ind-ℕ P ( zero-strong-ind-ℕ P p0) ( succ-strong-ind-ℕ P pS)) comp-zero-strong-ind-ℕ : { l : Level} → (P : ℕ → UU l) (p0 : P zero-ℕ) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → Id (strong-ind-ℕ P p0 pS zero-ℕ) p0 comp-zero-strong-ind-ℕ P p0 pS = refl comp-succ-strong-ind-ℕ : { l : Level} (P : ℕ → UU l) (p0 : P zero-ℕ) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) → ( n : ℕ) → Id (strong-ind-ℕ P p0 pS (succ-ℕ n)) (pS n (λ m p → strong-ind-ℕ P p0 pS m)) comp-succ-strong-ind-ℕ P p0 pS n = {! ap (succ-strong-ind-ℕ P pS n ? ?) ?!} ∙ ( eq-succ-strong-ind-ℕ P pS n ( λ m p → strong-ind-ℕ P p0 pS m) ( reflexive-leq-ℕ n) ( refl)) {- succ-comp-strong-ind-ℕ : { l : Level} → (P : ℕ → UU l) (p0 : P zero-ℕ) → ( pS : (k : ℕ) → (fam-strong-ind-ℕ P k) → P (succ-ℕ k)) (n : ℕ) → Id (strong-ind-ℕ P p0 pS (succ-ℕ n)) (pS n {!!}) succ-comp-strong-ind-ℕ P p0 pS = {!refl!} -} -- We show that induction on ℕ implies ordinal induction. fam-ordinal-ind-ℕ : { l : Level} → (ℕ → UU l) → ℕ → UU l fam-ordinal-ind-ℕ P n = (m : ℕ) → (le-ℕ m n) → P m le-zero-ℕ : (m : ℕ) → (le-ℕ m zero-ℕ) → empty le-zero-ℕ zero-ℕ () le-zero-ℕ (succ-ℕ m) () zero-ordinal-ind-ℕ : { l : Level} (P : ℕ → UU l) → fam-ordinal-ind-ℕ P zero-ℕ zero-ordinal-ind-ℕ P m t = ind-empty (le-zero-ℕ m t) le-one-ℕ : (n : ℕ) → le-ℕ (succ-ℕ n) one-ℕ → empty le-one-ℕ zero-ℕ () le-one-ℕ (succ-ℕ n) () transitive-le-ℕ' : (k l m : ℕ) → (le-ℕ k l) → (le-ℕ l (succ-ℕ m)) → le-ℕ k m transitive-le-ℕ' zero-ℕ zero-ℕ m () s transitive-le-ℕ' (succ-ℕ k) zero-ℕ m () s transitive-le-ℕ' zero-ℕ (succ-ℕ l) zero-ℕ star s = ind-empty (le-one-ℕ l s) transitive-le-ℕ' (succ-ℕ k) (succ-ℕ l) zero-ℕ t s = ind-empty (le-one-ℕ l s) transitive-le-ℕ' zero-ℕ (succ-ℕ l) (succ-ℕ m) star s = star transitive-le-ℕ' (succ-ℕ k) (succ-ℕ l) (succ-ℕ m) t s = transitive-le-ℕ' k l m t s succ-ordinal-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( (n : ℕ) → (fam-ordinal-ind-ℕ P n) → P n) → ( k : ℕ) → fam-ordinal-ind-ℕ P k → fam-ordinal-ind-ℕ P (succ-ℕ k) succ-ordinal-ind-ℕ P f k g m t = f m (λ m' t' → g m' (transitive-le-ℕ' m' m k t' t)) induction-ordinal-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( qS : (k : ℕ) → fam-ordinal-ind-ℕ P k → fam-ordinal-ind-ℕ P (succ-ℕ k)) ( n : ℕ) → fam-ordinal-ind-ℕ P n induction-ordinal-ind-ℕ P qS zero-ℕ = zero-ordinal-ind-ℕ P induction-ordinal-ind-ℕ P qS (succ-ℕ n) = qS n (induction-ordinal-ind-ℕ P qS n) conclusion-ordinal-ind-ℕ : { l : Level} (P : ℕ → UU l) → (( n : ℕ) → fam-ordinal-ind-ℕ P n) → (n : ℕ) → P n conclusion-ordinal-ind-ℕ P f n = f (succ-ℕ n) n (succ-le-ℕ n) ordinal-ind-ℕ : { l : Level} (P : ℕ → UU l) → ( (n : ℕ) → (fam-ordinal-ind-ℕ P n) → P n) → ( n : ℕ) → P n ordinal-ind-ℕ P f = conclusion-ordinal-ind-ℕ P ( induction-ordinal-ind-ℕ P (succ-ordinal-ind-ℕ P f)) {- The Pigeon hole principle. -} {- First we write a function that counts the number of elements in a decidable subset of a finite set. -} count-Fin-succ-ℕ : {l : Level} (n : ℕ) (P : Fin (succ-ℕ n) → classical-Prop l) → ℕ → is-decidable (pr1 (pr1 (P (inr star)))) → ℕ count-Fin-succ-ℕ n P m (inl x) = succ-ℕ m count-Fin-succ-ℕ n P m (inr x) = m count-Fin : {l : Level} (n : ℕ) (P : Fin n → classical-Prop l) → ℕ count-Fin zero-ℕ P = zero-ℕ count-Fin (succ-ℕ n) P = count-Fin-succ-ℕ n P ( count-Fin n (P ∘ inl)) ( pr2 (P (inr star))) {- Next we prove the pigeonhole principle. -} max-Fin : (n : ℕ) → Fin (succ-ℕ n) max-Fin n = inr star contraction-Fin-one-ℕ : (t : Fin one-ℕ) → Id (inr star) t contraction-Fin-one-ℕ (inr star) = refl is-contr-Fin-one-ℕ : is-contr (Fin one-ℕ) is-contr-Fin-one-ℕ = pair (inr star) contraction-Fin-one-ℕ skip : (n : ℕ) → Fin (succ-ℕ n) → Fin n → Fin (succ-ℕ n) skip (succ-ℕ n) (inl i) (inl j) = inl (skip n i j) skip (succ-ℕ n) (inl i) (inr star) = inr star skip (succ-ℕ n) (inr star) j = inl j repeat : (n : ℕ) → Fin n → Fin (succ-ℕ n) → Fin n repeat (succ-ℕ n) (inl i) (inl j) = inl (repeat n i j) repeat (succ-ℕ n) (inl j) (inr star) = inr star repeat (succ-ℕ n) (inr star) (inl j) = j repeat (succ-ℕ n) (inr star) (inr star) = inr star repeat-repeat : (n : ℕ) (i j : Fin n) → ((repeat n i) ∘ (repeat (succ-ℕ n) (skip n (inl i) j))) ~ ((repeat n j) ∘ (repeat (succ-ℕ n) (skip n (inl j) i))) repeat-repeat zero-ℕ () j k repeat-repeat (succ-ℕ n) (inl i) (inl j) (inl k) = ap inl (repeat-repeat n i j k) repeat-repeat (succ-ℕ n) (inl i) (inl j) (inr star) = refl repeat-repeat (succ-ℕ n) (inl i) (inr star) (inr star) = refl repeat-repeat (succ-ℕ n) (inr star) (inl j) (inr star) = refl repeat-repeat (succ-ℕ n) (inr star) (inr star) (inl k) = refl repeat-repeat (succ-ℕ n) (inr star) (inr star) (inr star) = refl repeat-repeat (succ-ℕ zero-ℕ) (inl ()) (inr star) (inl k) repeat-repeat (succ-ℕ (succ-ℕ n)) (inl i) (inr star) (inl k) = refl repeat-repeat (succ-ℕ zero-ℕ) (inr star) (inl ()) (inl k) repeat-repeat (succ-ℕ (succ-ℕ n)) (inr star) (inl j) (inl k) = refl {- skip-repeat : (n : ℕ) (i : Fin n) → ((skip n (inl i)) ∘ (repeat n i)) ~ id skip-repeat (succ-ℕ n) (inl x) (inl y) = ap inl (skip-repeat n x y) skip-repeat (succ-ℕ n) (inl x) (inr star) = refl skip-repeat (succ-ℕ n) (inr star) (inl (inl x)) = ap inl {!ap (skip n) ?!} skip-repeat (succ-ℕ n) (inr star) (inl (inr star)) = {!!} skip-repeat (succ-ℕ n) (inr star) (inr star) = {!!} -} map-lift-Fin : (m n : ℕ) (f : Fin (succ-ℕ m) → Fin (succ-ℕ n)) (i : Fin (succ-ℕ n)) (H : fib f i → empty) → Fin m → Fin n map-lift-Fin m n f (inl i) H = (repeat n i) ∘ (f ∘ inl) map-lift-Fin m (succ-ℕ n) f (inr star) H = ( repeat (succ-ℕ n) (max-Fin n)) ∘ ( f ∘ inl) map-lift-Fin zero-ℕ zero-ℕ f (inr star) H = ind-empty map-lift-Fin (succ-ℕ m) zero-ℕ f (inr star) H = ex-falso ( H (pair (inr star) (inv (contraction-Fin-one-ℕ (f (inr star)))))) {- is-lift-lift-Fin : (m n : ℕ) (f : Fin (succ-ℕ m) → Fin (succ-ℕ n)) (i : Fin (succ-ℕ n)) (H : fib f i → empty) → (f ∘ inl) ~ ((skip n i) ∘ (map-lift-Fin m n f i H)) is-lift-lift-Fin m n f (inl i) H x = {!!} is-lift-lift-Fin m n f (inr i) H x = {!!} -} -- The greatest common divisor {- First we show that mul-ℕ n is an embedding whenever n > 0. In order to do this, we have to show that add-ℕ n is injective. -} is-injective-add-ℕ' : (n : ℕ) → is-injective is-set-ℕ is-set-ℕ (λ m → add-ℕ m n) is-injective-add-ℕ' zero-ℕ k l p = p is-injective-add-ℕ' (succ-ℕ n) k l p = is-injective-add-ℕ' n k l (is-injective-succ-ℕ (add-ℕ k n) (add-ℕ l n) p) is-injective-add-ℕ : (n : ℕ) → is-injective is-set-ℕ is-set-ℕ (add-ℕ n) is-injective-add-ℕ n k l p = is-injective-add-ℕ' n k l (((commutative-add-ℕ k n) ∙ p) ∙ (commutative-add-ℕ n l)) is-emb-add-ℕ : (n : ℕ) → is-emb (add-ℕ n) is-emb-add-ℕ n = is-emb-is-injective is-set-ℕ is-set-ℕ (add-ℕ n) (is-injective-add-ℕ n) equiv-fib-add-fib-add-ℕ' : (m n : ℕ) → fib (add-ℕ' m) n ≃ fib (add-ℕ m) n equiv-fib-add-fib-add-ℕ' m n = equiv-tot (λ k → equiv-concat (commutative-add-ℕ m k) n) leq-fib-add-ℕ' : (m n : ℕ) → fib (add-ℕ' m) n → (leq-ℕ m n) leq-fib-add-ℕ' zero-ℕ n (pair k p) = leq-zero-ℕ n leq-fib-add-ℕ' (succ-ℕ m) (succ-ℕ n) (pair k p) = leq-fib-add-ℕ' m n (pair k (is-injective-succ-ℕ (add-ℕ k m) n p)) leq-fib-add-ℕ : (m n : ℕ) → fib (add-ℕ m) n → (leq-ℕ m n) leq-fib-add-ℕ m .m (pair zero-ℕ refl) = reflexive-leq-ℕ m leq-fib-add-ℕ m .(add-ℕ m (succ-ℕ k)) (pair (succ-ℕ k) refl) = transitive-leq-ℕ m (add-ℕ m k) (succ-ℕ (add-ℕ m k)) ( leq-fib-add-ℕ m (add-ℕ m k) (pair k refl)) ( succ-leq-ℕ (add-ℕ m k)) fib-add-leq-ℕ : (m n : ℕ) → (leq-ℕ m n) → fib (add-ℕ m) n fib-add-leq-ℕ zero-ℕ zero-ℕ star = pair zero-ℕ refl fib-add-leq-ℕ zero-ℕ (succ-ℕ n) star = {!!} fib-add-leq-ℕ (succ-ℕ m) (succ-ℕ n) p = {!!} {- fib-add-leq-ℕ zero-ℕ zero-ℕ H = pair zero-ℕ refl fib-add-leq-ℕ zero-ℕ (succ-ℕ n) H = pair (succ-ℕ n) refl fib-add-leq-ℕ (succ-ℕ m) (succ-ℕ n) H = pair ( pr1 (fib-add-leq-ℕ m n H)) ( ap succ-ℕ (pr2 (fib-add-leq-ℕ m n H))) -} is-equiv-leq-fib-add-ℕ : (m n : ℕ) → is-equiv (leq-fib-add-ℕ m n) is-equiv-leq-fib-add-ℕ m n = is-equiv-is-prop ( is-prop-map-is-emb _ (is-emb-add-ℕ m) n) ( is-prop-leq-ℕ m n) ( fib-add-leq-ℕ m n) is-equiv-fib-add-leq-ℕ : (m n : ℕ) → is-equiv (fib-add-leq-ℕ m n) is-equiv-fib-add-leq-ℕ m n = is-equiv-is-prop ( is-prop-leq-ℕ m n) ( is-prop-map-is-emb _ (is-emb-add-ℕ m) n) ( leq-fib-add-ℕ m n) is-injective-mul-ℕ : (n : ℕ) → (le-ℕ zero-ℕ n) → is-injective is-set-ℕ is-set-ℕ (mul-ℕ n) is-injective-mul-ℕ (succ-ℕ n) star zero-ℕ zero-ℕ p = refl is-injective-mul-ℕ (succ-ℕ n) star zero-ℕ (succ-ℕ l) p = ind-empty ( Eq-ℕ-eq ( zero-ℕ) ( succ-ℕ (add-ℕ (mul-ℕ n (succ-ℕ l)) l)) ( ( inv (right-zero-law-mul-ℕ n)) ∙ ( ( inv (right-unit-law-add-ℕ (mul-ℕ n zero-ℕ))) ∙ ( p ∙ (right-successor-law-add-ℕ (mul-ℕ n (succ-ℕ l)) l))))) is-injective-mul-ℕ (succ-ℕ n) star (succ-ℕ k) zero-ℕ p = ind-empty ( Eq-ℕ-eq ( succ-ℕ (add-ℕ (mul-ℕ n (succ-ℕ k)) k)) ( zero-ℕ) ( ( inv (right-successor-law-add-ℕ (mul-ℕ n (succ-ℕ k)) k)) ∙ ( p ∙ ( right-zero-law-mul-ℕ (succ-ℕ n))))) is-injective-mul-ℕ (succ-ℕ n) star (succ-ℕ k) (succ-ℕ l) p = ap succ-ℕ ( is-injective-mul-ℕ (succ-ℕ n) star k l ( is-injective-add-ℕ (succ-ℕ n) ( mul-ℕ (succ-ℕ n) k) ( mul-ℕ (succ-ℕ n) l) ( ( inv (right-successor-law-mul-ℕ (succ-ℕ n) k) ∙ p) ∙ ( right-successor-law-mul-ℕ (succ-ℕ n) l)))) is-emb-mul-ℕ : (n : ℕ) → (le-ℕ zero-ℕ n) → is-emb (mul-ℕ n) is-emb-mul-ℕ n le = is-emb-is-injective is-set-ℕ is-set-ℕ ( mul-ℕ n) ( is-injective-mul-ℕ n le) is-emb-mul-ℕ' : (n : ℕ) → (le-ℕ zero-ℕ n) → is-emb (λ m → mul-ℕ m n) is-emb-mul-ℕ' n t = is-emb-htpy' ( mul-ℕ n) ( λ m → mul-ℕ m n) ( commutative-mul-ℕ n) ( is-emb-mul-ℕ n t) {- We conclude that the division relation is a property. -} div-ℕ : ℕ → ℕ → UU lzero div-ℕ m n = Σ ℕ (λ k → Id (mul-ℕ k m) n) is-prop-div-ℕ : (m n : ℕ) → (le-ℕ zero-ℕ m) → is-prop (div-ℕ m n) is-prop-div-ℕ (succ-ℕ m) n star = is-prop-map-is-emb ( λ z → mul-ℕ z (succ-ℕ m)) ( is-emb-mul-ℕ' (succ-ℕ m) star) n {- We now construct the division with remainder. -} le-mul-ℕ : (d n k : ℕ) → UU lzero le-mul-ℕ d n k = le-ℕ n (mul-ℕ k d) is-decidable-le-mul-ℕ : (d n k : ℕ) → is-decidable (le-mul-ℕ d n k) is-decidable-le-mul-ℕ d n k = is-decidable-le-ℕ n (mul-ℕ k d) order-preserving-succ-ℕ : (n n' : ℕ) → (leq-ℕ n n') → (leq-ℕ (succ-ℕ n) (succ-ℕ n')) order-preserving-succ-ℕ n n' H = H order-preserving-add-ℕ : (m n m' n' : ℕ) → (leq-ℕ m m') → (leq-ℕ n n') → (leq-ℕ (add-ℕ m n) (add-ℕ m' n')) order-preserving-add-ℕ = {!!} {- order-preserving-add-ℕ zero-ℕ zero-ℕ m' n' Hm Hn = star order-preserving-add-ℕ zero-ℕ (succ-ℕ n) zero-ℕ (succ-ℕ n') Hm Hn = Hn order-preserving-add-ℕ zero-ℕ (succ-ℕ n) (succ-ℕ m') (succ-ℕ n') Hm Hn = leq-eq-right-ℕ n ( inv (right-successor-law-add-ℕ m' n')) ( order-preserving-add-ℕ zero-ℕ n (succ-ℕ m') n' Hm Hn) order-preserving-add-ℕ (succ-ℕ m) n (succ-ℕ m') n' Hm Hn = order-preserving-add-ℕ m n m' n' Hm Hn -} le-eq-right-ℕ : (m : ℕ) {n n' : ℕ} → Id n n' → le-ℕ m n' → le-ℕ m n le-eq-right-ℕ m refl = id le-add-ℕ : (m n : ℕ) → (leq-ℕ one-ℕ n) → le-ℕ m (add-ℕ m n) le-add-ℕ = {!!} {- le-add-ℕ zero-ℕ (succ-ℕ n) star = star le-add-ℕ (succ-ℕ m) (succ-ℕ n) star = le-add-ℕ m (succ-ℕ n) star -} le-mul-self-ℕ : (d n : ℕ) → (leq-ℕ one-ℕ d) → (leq-ℕ one-ℕ n) → le-mul-ℕ d n n le-mul-self-ℕ (succ-ℕ d) (succ-ℕ n) star star = le-eq-right-ℕ ( succ-ℕ n) ( right-successor-law-mul-ℕ (succ-ℕ n) d) ( le-add-ℕ (succ-ℕ n) (mul-ℕ (succ-ℕ n) d) {!leq-eq-right-ℕ !}) leq-multiple-ℕ : (n m : ℕ) → (leq-ℕ one-ℕ m) → leq-ℕ n (mul-ℕ n m) leq-multiple-ℕ n (succ-ℕ m) H = leq-eq-right-ℕ n ( inv (right-successor-law-mul-ℕ n m)) ( leq-fib-add-ℕ n (add-ℕ n (mul-ℕ n m)) (pair (mul-ℕ n m) refl)) least-factor-least-larger-multiple-ℕ : (d n : ℕ) → (leq-ℕ one-ℕ d) → minimal-element-ℕ (λ k → leq-ℕ n (mul-ℕ k d)) least-factor-least-larger-multiple-ℕ d n H = well-ordering-principle-ℕ ( λ k → leq-ℕ n (mul-ℕ k d)) ( λ k → is-decidable-leq-ℕ n (mul-ℕ k d)) ( pair n (leq-multiple-ℕ n d H)) factor-least-larger-multiple-ℕ : (d n : ℕ) → (leq-ℕ one-ℕ d) → ℕ factor-least-larger-multiple-ℕ d n H = pr1 (least-factor-least-larger-multiple-ℕ d n H) least-larger-multiple-ℕ : (d n : ℕ) → (leq-ℕ one-ℕ d) → ℕ least-larger-multiple-ℕ d n H = mul-ℕ (factor-least-larger-multiple-ℕ d n H) d leq-least-larger-multiple-ℕ : (d n : ℕ) (H : leq-ℕ one-ℕ d) → leq-ℕ n (least-larger-multiple-ℕ d n H) leq-least-larger-multiple-ℕ d n H = pr1 (pr2 (least-factor-least-larger-multiple-ℕ d n H)) is-minimal-least-larger-multiple-ℕ : (d n : ℕ) (H : leq-ℕ one-ℕ d) (k : ℕ) (K : leq-ℕ n (mul-ℕ k d)) → leq-ℕ (factor-least-larger-multiple-ℕ d n H) k is-minimal-least-larger-multiple-ℕ d n H = pr2 (pr2 (least-factor-least-larger-multiple-ℕ d n H)) is-decidable-div-is-decidable-eq-least-larger-multiple-ℕ : (d n : ℕ) (H : leq-ℕ one-ℕ d) → is-decidable (Id (least-larger-multiple-ℕ d n H) n) → is-decidable (div-ℕ d n) is-decidable-div-is-decidable-eq-least-larger-multiple-ℕ d n H (inl p) = inl (pair (factor-least-larger-multiple-ℕ d n H) p) is-decidable-div-is-decidable-eq-least-larger-multiple-ℕ d n H (inr f) = inr (λ x → {!!}) is-decidable-div-ℕ' : (d n : ℕ) → (leq-ℕ one-ℕ d) → is-decidable (div-ℕ d n) is-decidable-div-ℕ' d n H = {!!} is-decidable-div-ℕ : (d n : ℕ) → is-decidable (div-ℕ d n) is-decidable-div-ℕ zero-ℕ zero-ℕ = inl (pair zero-ℕ refl) is-decidable-div-ℕ zero-ℕ (succ-ℕ n) = inr ( λ p → Eq-ℕ-eq zero-ℕ (succ-ℕ n) ((inv (right-zero-law-mul-ℕ (pr1 p))) ∙ (pr2 p))) is-decidable-div-ℕ (succ-ℕ d) n = is-decidable-div-ℕ' (succ-ℕ d) n (leq-zero-ℕ d) -- Operations on decidable bounded subsets of ℕ iterated-operation-ℕ : (strict-upper-bound : ℕ) (operation : ℕ → ℕ → ℕ) (base-value : ℕ) → ℕ iterated-operation-ℕ zero-ℕ μ e = e iterated-operation-ℕ (succ-ℕ b) μ e = μ (iterated-operation-ℕ b μ e) b iterated-sum-ℕ : (summand : ℕ → ℕ) (b : ℕ) → ℕ iterated-sum-ℕ f zero-ℕ = zero-ℕ iterated-sum-ℕ f (succ-ℕ b) = add-ℕ (iterated-sum-ℕ f b) (f (succ-ℕ b)) ranged-sum-ℕ : (summand : ℕ → ℕ) (l u : ℕ) → ℕ ranged-sum-ℕ f zero-ℕ u = iterated-sum-ℕ f u ranged-sum-ℕ f (succ-ℕ l) zero-ℕ = zero-ℕ ranged-sum-ℕ f (succ-ℕ l) (succ-ℕ u) = ranged-sum-ℕ (f ∘ succ-ℕ) l u succ-iterated-operation-fam-ℕ : { l : Level} ( P : ℕ → UU l) (is-decidable-P : (n : ℕ) → is-decidable (P n)) → ( predecessor-strict-upper-bound : ℕ) (operation : ℕ → ℕ → ℕ) → is-decidable (P predecessor-strict-upper-bound) → ℕ → ℕ succ-iterated-operation-fam-ℕ P is-decidable-P b μ (inl p) m = μ m b succ-iterated-operation-fam-ℕ P is-decidable-P b μ (inr f) m = m iterated-operation-fam-ℕ : { l : Level} (P : ℕ → UU l) (is-decidable-P : (n : ℕ) → is-decidable (P n)) → ( strict-upper-bound : ℕ) (operation : ℕ → ℕ → ℕ) (base-value : ℕ) → ℕ iterated-operation-fam-ℕ P d zero-ℕ μ e = e iterated-operation-fam-ℕ P d (succ-ℕ b) μ e = succ-iterated-operation-fam-ℕ P d b μ (d b) ( iterated-operation-fam-ℕ P d b μ e) Sum-fam-ℕ : { l : Level} (P : ℕ → UU l) (is-decidable-P : (n : ℕ) → is-decidable (P n)) → ( upper-bound : ℕ) ( summand : ℕ → ℕ) → ℕ Sum-fam-ℕ P d b f = iterated-operation-fam-ℕ P d (succ-ℕ b) (λ x y → add-ℕ x (f y)) zero-ℕ {- iterated-operation-fam-ℕ P is-decidable-P zero-ℕ is-bounded-P μ base-value = base-value iterated-operation-fam-ℕ P is-decidable-P (succ-ℕ b) is-bounded-P μ base-value = succ-iterated-operation-ℕ P is-decidable-P b is-bounded-P μ ( is-decidable-P b) ( iterated-operation-ℕ ( introduce-bound-on-fam-ℕ b P) ( is-decidable-introduce-bound-on-fam-ℕ b P is-decidable-P) ( b) ( is-bounded-introduce-bound-on-fam-ℕ b P) ( μ) ( base-value)) product-decidable-bounded-fam-ℕ : { l : Level} (P : ℕ → UU l) → ( is-decidable-P : (n : ℕ) → is-decidable (P n)) ( b : ℕ) ( is-bounded-P : is-bounded-fam-ℕ b P) → ℕ product-decidable-bounded-fam-ℕ P is-decidable-P b is-bounded-P = iterated-operation-ℕ P is-decidable-P b is-bounded-P mul-ℕ one-ℕ twenty-four-ℕ : ℕ twenty-four-ℕ = product-decidable-bounded-fam-ℕ ( λ x → le-ℕ x five-ℕ) ( λ x → is-decidable-le-ℕ x five-ℕ) ( five-ℕ) ( λ x → id) -} {- test-zero-twenty-four-ℕ : Id twenty-four-ℕ zero-ℕ test-zero-twenty-four-ℕ = refl test-twenty-four-ℕ : Id twenty-four-ℕ (factorial four-ℕ) test-twenty-four-ℕ = refl -} -- Exercises -- Exercise 10.? abstract has-decidable-equality-𝟚 : has-decidable-equality bool has-decidable-equality-𝟚 true true = inl refl has-decidable-equality-𝟚 true false = inr (Eq-𝟚-eq true false) has-decidable-equality-𝟚 false true = inr (Eq-𝟚-eq false true) has-decidable-equality-𝟚 false false = inl refl -- Exercise 10.? abstract has-decidable-equality-prod' : {l1 l2 : Level} {A : UU l1} {B : UU l2} → (x x' : A) (y y' : B) → is-decidable (Id x x') → is-decidable (Id y y') → is-decidable (Id (pair x y) (pair x' y')) has-decidable-equality-prod' x x' y y' (inl p) (inl q) = inl (eq-pair-triv (pair p q)) has-decidable-equality-prod' x x' y y' (inl p) (inr g) = inr (λ h → g (ap pr2 h)) has-decidable-equality-prod' x x' y y' (inr f) (inl q) = inr (λ h → f (ap pr1 h)) has-decidable-equality-prod' x x' y y' (inr f) (inr g) = inr (λ h → f (ap pr1 h)) abstract has-decidable-equality-prod : {l1 l2 : Level} {A : UU l1} {B : UU l2} → has-decidable-equality A → has-decidable-equality B → has-decidable-equality (A × B) has-decidable-equality-prod dec-A dec-B (pair x y) (pair x' y') = has-decidable-equality-prod' x x' y y' (dec-A x x') (dec-B y y') {- bounds-fam-ℕ : {l : Level} (P : ℕ → UU l) → UU l bounds-fam-ℕ P = Σ ℕ (λ n → is-bounded-fam-ℕ n P) is-minimal-ℕ : {l : Level} (P : ℕ → UU l) → Σ ℕ P → UU l is-minimal-ℕ P (pair n p) = (t : Σ ℕ P) → leq-ℕ n (pr1 t) eq-zero-leq-zero-ℕ : (n : ℕ) → leq-ℕ n zero-ℕ → Id n zero-ℕ eq-zero-leq-zero-ℕ zero-ℕ star = refl eq-zero-leq-zero-ℕ (succ-ℕ n) () fam-succ-ℕ : {l : Level} → (ℕ → UU l) → (ℕ → UU l) fam-succ-ℕ P n = P (succ-ℕ n) is-decidable-fam-succ-ℕ : {l : Level} (P : ℕ → UU l) → ((n : ℕ) → is-decidable (P n)) → ((n : ℕ) → is-decidable (P (succ-ℕ n))) is-decidable-fam-succ-ℕ P d n = d (succ-ℕ n) min-is-bounded-not-zero-ℕ : {l : Level} (P : ℕ → UU l) → ((n : ℕ) → is-decidable (P n)) → Σ ℕ (λ n → is-bounded-fam-ℕ n P) → ¬ (P zero-ℕ) → Σ (Σ ℕ (fam-succ-ℕ P)) (is-minimal-ℕ (fam-succ-ℕ P)) → Σ (Σ ℕ P) (is-minimal-ℕ P) min-is-bounded-not-zero-ℕ P d b np0 t = {!!} min-is-bounded-ℕ : {l : Level} (P : ℕ → UU l) → ((n : ℕ) → is-decidable (P n)) → Σ ℕ (λ n → is-bounded-fam-ℕ n P) → Σ ℕ P → Σ (Σ ℕ P) (is-minimal-ℕ P) min-is-bounded-ℕ P d (pair zero-ℕ b) t = pair ( pair ( zero-ℕ) ( tr P (eq-zero-leq-zero-ℕ (pr1 t) (b (pr1 t) (pr2 t))) (pr2 t))) ( λ p → leq-zero-ℕ (pr1 p)) min-is-bounded-ℕ P d (pair (succ-ℕ n) b) t = ind-coprod ( λ (t : is-decidable (P zero-ℕ)) → Σ (Σ ℕ P) (is-minimal-ℕ P)) ( λ p0 → pair (pair zero-ℕ p0) (λ p → leq-zero-ℕ (pr1 p))) ( λ y → min-is-bounded-not-zero-ℕ P d (pair (succ-ℕ n) b) y ( min-is-bounded-ℕ ( fam-succ-ℕ P) ( is-decidable-fam-succ-ℕ P d) {!!} {!!})) ( d zero-ℕ) {- We show that every non-empty decidable subset of ℕ has a least element. -} least-ℕ : {l : Level} (P : ℕ → UU l) → Σ ℕ P → UU l least-ℕ P (pair n p) = (m : ℕ) → P m → leq-ℕ n m least-element-non-empty-decidable-subset-ℕ : {l : Level} (P : ℕ → UU l) (d : (n : ℕ) → is-decidable (P n)) → Σ ℕ P → Σ (Σ ℕ P) (least-ℕ P) least-element-non-empty-decidable-subset-ℕ P d (pair zero-ℕ p) = pair (pair zero-ℕ p) {!!} least-element-non-empty-decidable-subset-ℕ P d (pair (succ-ℕ n) p) = {!!} -} zero-Fin : (n : ℕ) → Fin (succ-ℕ n) zero-Fin zero-ℕ = inr star zero-Fin (succ-ℕ n) = inl (zero-Fin n) succ-Fin : (n : ℕ) → Fin n → Fin n succ-Fin (succ-ℕ n) (inr star) = zero-Fin n succ-Fin (succ-ℕ (succ-ℕ n)) (inl (inl x)) = inl (succ-Fin (succ-ℕ n) (inl x)) succ-Fin (succ-ℕ (succ-ℕ n)) (inl (inr star)) = inr star iterated-succ-Fin : (k : ℕ) → (n : ℕ) → Fin n → Fin n iterated-succ-Fin zero-ℕ n = id iterated-succ-Fin (succ-ℕ k) n = (succ-Fin n) ∘ (iterated-succ-Fin k n) quotient-ℕ-Fin : (n : ℕ) → Fin (succ-ℕ n) quotient-ℕ-Fin n = iterated-succ-Fin n (succ-ℕ n) (zero-Fin n) pred-Fin : (n : ℕ) → Fin n → Fin n pred-Fin (succ-ℕ zero-ℕ) (inr star) = inr star pred-Fin (succ-ℕ (succ-ℕ n)) (inl x) = {!!} pred-Fin (succ-ℕ (succ-ℕ n)) (inr star) = inl (inr star) add-Fin : (n : ℕ) → Fin n → Fin n → Fin n add-Fin (succ-ℕ n) (inl x) j = {!!} add-Fin (succ-ℕ n) (inr x) j = {!!} idempotent-succ-Fin : (n : ℕ) (i : Fin n) → Id (iterated-succ-Fin n n i) i idempotent-succ-Fin (succ-ℕ zero-ℕ) (inr star) = refl idempotent-succ-Fin (succ-ℕ (succ-ℕ n)) (inl x) = {!!} idempotent-succ-Fin (succ-ℕ (succ-ℕ n)) (inr x) = {!!} in-nat-ℤ : ℕ → ℤ in-nat-ℤ zero-ℕ = zero-ℤ in-nat-ℤ (succ-ℕ n) = in-pos n div-ℤ : (k l : ℤ) → UU lzero div-ℤ k l = Σ ℤ (λ x → Id (mul-ℤ x k) l) _≡_mod_ : (k l : ℤ) (n : ℕ) → UU lzero k ≡ l mod n = div-ℤ (in-nat-ℤ n) (add-ℤ k (neg-ℤ l)) -- From before is-even-ℕ : ℕ → UU lzero is-even-ℕ n = div-ℕ two-ℕ n is-prime : ℕ → UU lzero is-prime n = (one-ℕ < n) × ((m : ℕ) → (one-ℕ < m) → (div-ℕ m n) → Id m n) {- The Goldbach conjecture asserts that every even number above 2 is the sum of two primes. -} Goldbach-conjecture : UU lzero Goldbach-conjecture = ( n : ℕ) → (two-ℕ < n) → (is-even-ℕ n) → Σ ℕ (λ p → (is-prime p) × (Σ ℕ (λ q → (is-prime q) × Id (add-ℕ p q) n))) is-twin-prime : ℕ → UU lzero is-twin-prime n = (is-prime n) × (is-prime (succ-ℕ (succ-ℕ n))) {- The twin prime conjecture asserts that there are infinitely many twin primes. We assert that there are infinitely twin primes by asserting that for every n : ℕ there is a twin prime that is larger than n. -} Twin-prime-conjecture : UU lzero Twin-prime-conjecture = (n : ℕ) → Σ ℕ (λ p → (is-twin-prime p) × (leq-ℕ n p)) -- Exercise unit-classical-Prop : classical-Prop lzero unit-classical-Prop = pair (pair {!!} {!!}) {!!} raise-unit-classical-Prop : (l : Level) → classical-Prop l raise-unit-classical-Prop l = pair ( pair ( raise l unit) ( is-prop-is-equiv' unit ( map-raise l unit) ( is-equiv-map-raise l unit) ( is-prop-unit))) ( inl (map-raise l unit star)) bool-classical-Prop : (l : Level) → classical-Prop l → bool bool-classical-Prop l (pair P (inl x)) = true bool-classical-Prop l (pair P (inr x)) = false classical-Prop-bool : (l : Level) → bool → classical-Prop l classical-Prop-bool l true = raise-unit-classical-Prop l classical-Prop-bool l false = {!!} ",16342,True,3267.6390758340967,median "//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2006-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package mx.managers { import flash.display.DisplayObject; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.Timer; import mx.controls.ToolTip; import mx.core.FlexGlobals; import mx.core.FlexVersion; import mx.core.IFlexModule; import mx.core.IInvalidating; import mx.core.ILayoutDirectionElement; import mx.core.IToolTip; import mx.core.IUIComponent; import mx.core.LayoutDirection; import mx.core.mx_internal; import mx.effects.EffectManager; import mx.effects.IAbstractEffect; import mx.events.DynamicEvent; import mx.events.EffectEvent; import mx.events.ToolTipEvent; import mx.managers.IToolTipManagerClient; import mx.styles.IStyleClient; import mx.validators.IValidatorListener; use namespace mx_internal; [ExcludeClass] /** * @private * The ToolTipManager lets you set basic ToolTip and error tip functionality, * such as display delay and the disabling of ToolTips. * * @see mx.controls.ToolTip * @see mx.validators.Validator */ public class ToolTipManagerImpl extends EventDispatcher implements IToolTipManager2 { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private */ private static var instance:IToolTipManager2; /** * @private * * Place to hook in additional classes */ public static var mixins:Array; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * @private */ public static function getInstance():IToolTipManager2 { if (!instance) instance = new ToolTipManagerImpl(); return instance; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * @private */ public function ToolTipManagerImpl() { super(); if (instance) throw new Error(""Instance already exists.""); if (mixins) { var n:int = mixins.length; for (var i:int = 0; i < n; i++) { new mixins[i](this); } } if (hasEventListener(""initialize"")) dispatchEvent(new Event(""initialize"")); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * A flag that keeps track of whether this class's initialize() * method has been executed. */ mx_internal var initialized:Boolean = false; /** * @private * This timer is used to delay the appearance of a normal ToolTip * after the mouse moves over a target; an error tip has no such delay. * *

This timer, which is lazily created, is started when the mouse * moves over an object with a ToolTip, with a duration specified * by showDelay. * If the mouse moves out of this object before the timer fires, * the ToolTip is never created. * If the mouse stays over the object until the timer fires, * the ToolTip is created and its showEffect is started. */ mx_internal var showTimer:Timer; /** * @private * This timer is used to make the tooltip ""time out"" and hide itself * if the mouse stays over a target. * *

This timer, which is lazily created, is started * when the showEffect ends. * When it fires, the hideEffect is started.

*/ mx_internal var hideTimer:Timer; /** * @private * This timer is used to implement mousing quickly over multiple targets * with ToolTip... * *

This timer, which is lazily created, is started * when ...

*/ mx_internal var scrubTimer:Timer; /** * @private */ mx_internal var currentText:String; /** * @private */ mx_internal var isError:Boolean; /** * The UIComponent with the ToolTip assigned to it * that was most recently under the mouse. * During much of the tool tip life cycle this property * has the same value as the currentTarget property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var previousTarget:DisplayObject; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // currentTarget //---------------------------------- /** * @private */ private var _currentTarget:DisplayObject; /** * The UIComponent that is currently displaying a ToolTip, * or null if none is. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get currentTarget():DisplayObject { return _currentTarget; } /** * @private */ public function set currentTarget(value:DisplayObject):void { _currentTarget = value; } //---------------------------------- // currentToolTip //---------------------------------- /** * @private */ mx_internal var _currentToolTip:DisplayObject; /** * The ToolTip object that is currently visible, * or null if none is shown. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get currentToolTip():IToolTip { return _currentToolTip as IToolTip; } /** * @private */ public function set currentToolTip(value:IToolTip):void { _currentToolTip = value as DisplayObject; if (hasEventListener(""currentToolTip"")) dispatchEvent(new Event(""currentToolTip"")); } //---------------------------------- // enabled //---------------------------------- /** * @private */ private var _enabled:Boolean = true; /** * If true, the ToolTipManager will automatically show * ToolTips when the user moves the mouse pointer over components. * If false, no ToolTips will be shown. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get enabled():Boolean { return _enabled; } /** * @private */ public function set enabled(value:Boolean):void { _enabled = value; } //---------------------------------- // hideDelay //---------------------------------- /** * @private */ private var _hideDelay:Number = 10000; // milliseconds /** * The amount of time, in milliseconds, that Flex waits * to hide the ToolTip after it appears. * Once Flex hides a ToolTip, the user must move the mouse * off the component and then back onto it to see the ToolTip again. * If you set hideDelay to Infinity, * Flex does not hide the ToolTip until the user triggers an event, * such as moving the mouse off of the component. * * @default 10000 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get hideDelay():Number { return _hideDelay; } /** * @private */ public function set hideDelay(value:Number):void { _hideDelay = value; } //---------------------------------- // hideEffect //---------------------------------- /** * @private */ private var _hideEffect:IAbstractEffect; /** * The effect that plays when a ToolTip is hidden, * or null if the ToolTip should disappear with no effect. * *

Effects are not marshaled across applicationDomains in a sandbox * as they may not be supportable in different versions

* * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get hideEffect():IAbstractEffect { return _hideEffect; } /** * @private */ public function set hideEffect(value:IAbstractEffect):void { _hideEffect = value as IAbstractEffect; } //---------------------------------- // scrubDelay //---------------------------------- /** * @private */ private var _scrubDelay:Number = 100; // milliseconds /** * The amount of time, in milliseconds, that a user can take * when moving the mouse between controls before Flex again waits * for the duration of showDelay to display a ToolTip. * *

This setting is useful if the user moves quickly from one control * to another; after displaying the first ToolTip, Flex will display * the others immediately rather than waiting. * The shorter the setting for scrubDelay, the more * likely that the user must wait for an amount of time specified * by showDelay in order to see the next ToolTip. * A good use of this property is if you have several buttons on a * toolbar, and the user will quickly scan across them to see brief * descriptions of their functionality.

* * @default 100 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get scrubDelay():Number { return _scrubDelay; } /** * @private */ public function set scrubDelay(value:Number):void { _scrubDelay = value; } //---------------------------------- // showDelay //---------------------------------- /** * @private */ private var _showDelay:Number = 500; // milliseconds /** * The amount of time, in milliseconds, that Flex waits * before displaying the ToolTip box once a user * moves the mouse over a component that has a ToolTip. * To make the ToolTip appear instantly, set showDelay to 0. * * @default 500 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get showDelay():Number { return _showDelay; } /** * @private */ public function set showDelay(value:Number):void { _showDelay = value; } //---------------------------------- // showEffect //---------------------------------- /** * @private */ private var _showEffect:IAbstractEffect; /** * The effect that plays when a ToolTip is shown, * or null if the ToolTip should appear with no effect. * *

Effects are not marshaled across applicationDomains in a sandbox * as they may not be supportable in different versions

* * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get showEffect():IAbstractEffect { return _showEffect; } /** * @private */ public function set showEffect(value:IAbstractEffect):void { _showEffect = value as IAbstractEffect; } //---------------------------------- // toolTipClass //---------------------------------- /** * @private */ private var _toolTipClass:Class = ToolTip; /** * The class to use for creating ToolTips. * *

The ToolTipClass is not marshaled across applicationDomains in a sandbox * as they may not be supportable in different versions. Child * applications should only be interested in setting the tooltip * for objects within themselves

* * @default mx.controls.ToolTip * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get toolTipClass():Class { return _toolTipClass; } /** * @private */ public function set toolTipClass(value:Class):void { _toolTipClass = value; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Initializes the class. * *

This method sets up three Timer objects that ToolTipManager * starts and stops while tracking the mouse. * The repeatCount is set to 1 so that they fire only once. * Their duration is set later, just before they are started. * The timers are never destroyed once they are created here.

* *

This method is called by targetChanged(); Flex waits to initialize * the class until mouse-tracking happens in order to optimize * startup time.

*/ mx_internal function initialize():void { if (!showTimer) { showTimer = new Timer(0, 1); showTimer.addEventListener(TimerEvent.TIMER, showTimer_timerHandler); } if (!hideTimer) { hideTimer = new Timer(0, 1); hideTimer.addEventListener(TimerEvent.TIMER, hideTimer_timerHandler); } if (!scrubTimer) scrubTimer = new Timer(0, 1); initialized = true; } /** * Registers a target UIComponent or UITextField, and the text * for its ToolTip, with the ToolTipManager. * This causes the ToolTipManager to display a ToolTip * when the mouse hovers over the target. * *

This method is called by the setter * for the toolTip property in UIComponent and UITextField.

* * @param target The UIComponent or UITextField that owns the ToolTip. * * @param oldToolTip The old text that was displayed * in the ToolTip. * * @param newToolTip The new text to display in the ToolTip. * If null, no ToolTip will be displayed when the mouse hovers * over the target. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function registerToolTip(target:DisplayObject, oldToolTip:String, newToolTip:String):void { if (!oldToolTip && newToolTip) { target.addEventListener(MouseEvent.MOUSE_OVER, toolTipMouseOverHandler); target.addEventListener(MouseEvent.MOUSE_OUT, toolTipMouseOutHandler); // If the mouse is already over the object // that's getting a toolTip, show the tip. if (mouseIsOver(target)) showImmediately(target); } else if (oldToolTip && !newToolTip) { target.removeEventListener(MouseEvent.MOUSE_OVER, toolTipMouseOverHandler); target.removeEventListener(MouseEvent.MOUSE_OUT, toolTipMouseOutHandler); // If the mouse is over the object whose toolTip // is being removed, hide the tip. if (mouseIsOver(target)) hideImmediately(target); } } /** * Registers a target UIComponent, and the text * for its error tip, with the ToolTipManager. * This causes the ToolTipManager to display an error tip * when the mouse hovers over the target. * *

This method is called by the setter * for the errorString property in UIComponent.

* * @param target The UIComponent or UITextField that owns the ToolTip. * * @param oldErrorString The old text that was displayed * in the error tip. * * @param newErrorString The new text to display in the error tip. * If null, no error tip will be displayed when the mouse hovers * over the target. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function registerErrorString(target:DisplayObject, oldErrorString:String, newErrorString:String):void { if (!oldErrorString && newErrorString) { target.addEventListener(MouseEvent.MOUSE_OVER, errorTipMouseOverHandler); target.addEventListener(MouseEvent.MOUSE_OUT, errorTipMouseOutHandler); // If the mouse is already over the object // that's getting an errorTip, show the tip. if (mouseIsOver(target)) showImmediately(target); } else if (oldErrorString && !newErrorString) { target.removeEventListener(MouseEvent.MOUSE_OVER, errorTipMouseOverHandler); target.removeEventListener(MouseEvent.MOUSE_OUT, errorTipMouseOutHandler); // If the mouse is over the object whose toolTip // is being removed, hide the tip. if (mouseIsOver(target)) hideImmediately(target); } } /** * @private * Returns true if the mouse is over the specified target. */ private function mouseIsOver(target:DisplayObject):Boolean { if (!target || !target.stage) return false; //SDK:13465 - If we pass through the above if block, then //we have a target component and its been added to the //display list. If the mouse coordinates are (0,0), there //is a chance the component has not been positioned yet //and we'll end up mistakenly showing tooltips since the //target hitTest will return true. if ((target.stage.mouseX == 0) && (target.stage.mouseY == 0)) return false; if (target is ILayoutManagerClient && !ILayoutManagerClient(target).initialized) return false; return target.hitTestPoint(target.stage.mouseX, target.stage.mouseY, true); } /** * @private * Shows the tip immediately when the toolTip or errorTip property * becomes non-null and the mouse is over the target. */ private function showImmediately(target:DisplayObject):void { var oldShowDelay:Number = ToolTipManager.showDelay; ToolTipManager.showDelay = 0; checkIfTargetChanged(target); ToolTipManager.showDelay = oldShowDelay; } /** * @private * Hides the tip immediately when the toolTip or errorTip property * becomes null and the mouse is over the target. */ private function hideImmediately(target:DisplayObject):void { checkIfTargetChanged(null); } /** * Replaces the ToolTip, if necessary. * *

Determines whether the UIComponent or UITextField object * with the ToolTip assigned to it that is currently under the mouse * pointer is the most recent such object. * If not, it removes the old ToolTip and displays the new one.

* * @param displayObject The UIComponent or UITextField that is currently under the mouse. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function checkIfTargetChanged(displayObject:DisplayObject):void { if (!enabled) return; findTarget(displayObject); if (currentTarget != previousTarget) { targetChanged(); previousTarget = currentTarget; } } /** * Searches from the displayObject object up the chain * of parent objects until it finds a UIComponent or UITextField object * with a toolTip or errorString property. * Treats an empty string as a valid toolTip property. * Sets the currentTarget property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function findTarget(displayObject:DisplayObject):void { // Walk up the DisplayObject parent chain looking for a UIComponent // with a toolTip or errorString property. Note that we stop // even if we find a tooltip which is an empty string. Although // we don't display empty tooltips, we have to track when we // are over a movieclip with an empty tooltip so that we can // hide any previous tooltip. This allows a child to set // toolTip="""" to ""cancel"" its parent's toolTip. while (displayObject) { if (displayObject is IValidatorListener) { currentText = IValidatorListener(displayObject).errorString; var showErrorTip:Boolean; if (displayObject is IStyleClient) showErrorTip = FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0 || IStyleClient(displayObject).getStyle(""showErrorTip""); ; if (currentText != null && currentText != """" && showErrorTip) { currentTarget = displayObject; isError = true; return; } } if (displayObject is IToolTipManagerClient) { currentText = IToolTipManagerClient(displayObject).toolTip; if (currentText != null) { currentTarget = displayObject; isError = false; return; } } displayObject = displayObject.parent; } currentText = null; currentTarget = null; } /** * Removes any ToolTip that is currently displayed and displays * the ToolTip for the UIComponent that is currently under the mouse * pointer, as determined by the currentTarget property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function targetChanged():void { // Do lazy creation of the Timer objects this class uses. if (!initialized) initialize() var event:ToolTipEvent; if (previousTarget && currentToolTip) { if (currentToolTip is IToolTip) { event = new ToolTipEvent(ToolTipEvent.TOOL_TIP_HIDE); event.toolTip = currentToolTip; previousTarget.dispatchEvent(event); } else { if (hasEventListener(ToolTipEvent.TOOL_TIP_HIDE)) dispatchEvent(new Event(ToolTipEvent.TOOL_TIP_HIDE)); } } reset(); if (currentTarget) { // Don't display empty tooltips. if (currentText == """") return; // Dispatch a ""startToolTip"" event // from the object displaying the tooltip. event = new ToolTipEvent(ToolTipEvent.TOOL_TIP_START); currentTarget.dispatchEvent(event); if (showDelay == 0 || scrubTimer.running) { // Create the tooltip and start its showEffect. createTip(); initializeTip(); positionTip(); showTip(); } else { showTimer.delay = showDelay; showTimer.start(); // After the delay, showTimer_timerHandler() // will create the tooltip and start its showEffect. } } } /** * Creates an invisible new ToolTip. * *

If the ToolTipManager's enabled property is * true this method is automatically called * when the user moves the mouse over an object that has * the toolTip property set, * The ToolTipManager makes subsequent calls to * initializeTip(), positionTip(), * and showTip() to complete the display * of the ToolTip.

* *

The type of ToolTip that is created is determined by the * toolTipClass property. * By default, this is the ToolTip class. * This class can be styled to appear as either a normal ToolTip * (which has a yellow background by default) or as an error tip * for validation errors (which is red by default).

* *

After creating the ToolTip with the new * operator, this method stores a reference to it in the * currentToolTip property. * It then uses addChild() to add this ToolTip to the * SystemManager's toolTips layer.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function createTip():void { // Dispatch a ""createToolTip"" event // from the object displaying the tooltip. var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_CREATE); currentTarget.dispatchEvent(event); if (event.toolTip) currentToolTip = event.toolTip; else currentToolTip = new toolTipClass(); currentToolTip.visible = false; // Set the tooltip to be in the same module factory as the target to the // correct style manager is used. Don't overwrite an existing module factory. if (currentToolTip is IFlexModule && IFlexModule(currentToolTip).moduleFactory == null && currentTarget is IFlexModule) IFlexModule(currentToolTip).moduleFactory = IFlexModule(currentTarget).moduleFactory; if (hasEventListener(""createTip"")) if (!dispatchEvent(new Event(""createTip"", false, true))) return; var sm:ISystemManager = getSystemManager(currentTarget) as ISystemManager; sm.topLevelSystemManager.toolTipChildren.addChild(currentToolTip as DisplayObject); } /** * Initializes a newly created ToolTip with the appropriate text, * based on the object under the mouse. * *

If the ToolTipManager's enabled property is * true this method is automatically called * when the user moves the mouse over an object that has * the toolTip property set. * The ToolTipManager calls createTip() before * this method, and positionTip() and * showTip() after.

* *

If a normal ToolTip is being displayed, this method * sets its text as specified by the toolTip * property of the object under the mouse. * If an error tip is being displayed, the text is as * specified by the errorString property * of the object under the mouse.

* *

This method also makes the ToolTip the appropriate * size for the text that it needs to display.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function initializeTip():void { // Set the text of the tooltip. if (currentToolTip is IToolTip) IToolTip(currentToolTip).text = currentText; if (isError && currentToolTip is IStyleClient) IStyleClient(currentToolTip).setStyle(""styleName"", ""errorTip""); sizeTip(currentToolTip); if (currentToolTip is IStyleClient) { // Set up its ""show"" and ""hide"" effects. if (showEffect) IStyleClient(currentToolTip).setStyle(""showEffect"", showEffect); if (hideEffect) IStyleClient(currentToolTip).setStyle(""hideEffect"", hideEffect); } if (showEffect || hideEffect) { currentToolTip.addEventListener(EffectEvent.EFFECT_END, effectEndHandler); } } /** * @private * Objects added to the SystemManager's ToolTip layer don't get * automatically measured or sized, so ToolTipManager has to * measure it and set its size. */ public function sizeTip(toolTip:IToolTip):void { // Force measure() to be called on the tooltip. // Otherwise, its measured size will be 0. if (toolTip is IInvalidating) IInvalidating(toolTip).validateNow(); toolTip.setActualSize( toolTip.getExplicitOrMeasuredWidth(), toolTip.getExplicitOrMeasuredHeight()); } /** * Positions a newly created and initialized ToolTip on the stage. * *

If the ToolTipManager's enabled property is * true this method is automatically called * when the user moves the mouse over an object that has * the toolTip property set. * The ToolTipManager calls createTip() and * initializeTip() before this method, * and showTip() after.

* *

If a normal ToolTip is being displayed, this method positions * its upper-left (upper-right) corner near the lower-right (lower-left) * of the arrow cursor. This method ensures that the ToolTip is * completely in view. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function positionTip():void { // Determine layoutDirection of the target component. var layoutDirection:String; if (currentTarget is ILayoutDirectionElement) layoutDirection = ILayoutDirectionElement(currentTarget).layoutDirection; else layoutDirection = LayoutDirection.LTR; const mirror:Boolean = (layoutDirection == LayoutDirection.RTL); var x:Number; var y:Number; var screenWidth:Number = currentToolTip.screen.width; var screenHeight:Number = currentToolTip.screen.height; if (isError) { // Tooltips are laid out in the same direction as the target // component. var tipElt:ILayoutDirectionElement = currentToolTip as ILayoutDirectionElement; if (tipElt && tipElt.layoutDirection != layoutDirection) { tipElt.layoutDirection = layoutDirection; // sizeTip below will call validateNow() tipElt.invalidateLayoutDirection(); } var targetGlobalBounds:Rectangle = getGlobalBounds(currentTarget, currentToolTip.root, mirror); x = mirror ? targetGlobalBounds.left - 4 : targetGlobalBounds.right + 4; y = targetGlobalBounds.top - 1; // If there's no room to the right (left) of the control, put it // above or below, with the left (right) edge of the error tip // aligned with the left (right) edge of the target. var noRoom:Boolean = mirror ? x < currentToolTip.width : x + currentToolTip.width > screenWidth; if (noRoom) { var newWidth:Number = NaN; var oldWidth:Number = NaN; x = mirror ? targetGlobalBounds.right + 2 - currentToolTip.width : targetGlobalBounds.left - 2; // If the error tip would be too wide for the stage, // reduce the maximum width to fit onstage. Note that // we have to reassign the text in order to get the tip // to relayout after changing the border style and maxWidth. if (mirror) { if (x < currentToolTip.width + 4) { // -4 on the left, +2 on the right = -2 x = 4; newWidth = targetGlobalBounds.right - 2; } } else { if (x + currentToolTip.width + 4 > screenWidth) newWidth = screenWidth - x - 4; } if (!isNaN(newWidth)) { oldWidth = Object(toolTipClass).maxWidth; Object(toolTipClass).maxWidth = newWidth; if (currentToolTip is IStyleClient) IStyleClient(currentToolTip).setStyle(""borderStyle"", ""errorTipAbove""); currentToolTip[""text""] = currentToolTip[""text""]; } // Even if the error tip will fit onstage, we still need to // change the border style and get the error tip to relayout. else { if (currentToolTip is IStyleClient) IStyleClient(currentToolTip).setStyle(""borderStyle"", ""errorTipAbove""); currentToolTip[""text""] = currentToolTip[""text""]; } if (currentToolTip.height + 2 < targetGlobalBounds.top) { // There's room to put it above the control. y = targetGlobalBounds.top - (currentToolTip.height + 2); } else { // No room above, put it below the control. y = targetGlobalBounds.bottom + 2; if (!isNaN(newWidth)) Object(toolTipClass).maxWidth = newWidth; if (currentToolTip is IStyleClient) IStyleClient(currentToolTip).setStyle(""borderStyle"", ""errorTipBelow""); currentToolTip[""text""] = currentToolTip[""text""]; } } // Since the border style of the error tip may have changed, // we have to force a remeasurement and change its size. // This is because objects in the toolTips layer // don't undergo normal measurement and layout. sizeTip(currentToolTip) // If we changed the tooltip max size, we change it back. // Otherwise, if RTL, and x wasn't set for maxWidth, reposition // because the width may have changed during the remeasure. if (!isNaN(oldWidth)) Object(toolTipClass).maxWidth = oldWidth; else if (mirror) x = targetGlobalBounds.right + 2 - currentToolTip.width; } else { var sm:ISystemManager = getSystemManager(currentTarget); // Position the upper-left (upper-right) of the tooltip // at the lower-right (lower-left) of the arrow cursor. x = DisplayObject(sm).mouseX + 11; if (mirror) x -= currentToolTip.width; y = DisplayObject(sm).mouseY + 22; // If the tooltip is too wide to fit onstage, move it left (right). var toolTipWidth:Number = currentToolTip.width; if (mirror) { if (x < 2) x = 2; } else if (x + toolTipWidth > screenWidth) { x = screenWidth - toolTipWidth; } // If the tooltip is too tall to fit onstage, move it up. var toolTipHeight:Number = currentToolTip.height; if (y + toolTipHeight > screenHeight) y = screenHeight - toolTipHeight; var pos:Point = new Point(x, y); pos = DisplayObject(sm).localToGlobal(pos); pos = DisplayObject(sm.getSandboxRoot()).globalToLocal(pos); x = pos.x; y = pos.y; } currentToolTip.move(x, y); } /** * Shows a newly created, initialized, and positioned ToolTip. * *

If the ToolTipManager's enabled property is * true this method is automatically called * when the user moves the mouse over an object that has * the toolTip property set. * The ToolTipManager calls createTip(), * initializeTip(), and positionTip() * before this method.

* *

This method first dispatches a ""showToolTip"" * event from the object under the mouse. * This gives you a chance to do special processing on a * particular object's ToolTip just before it becomes visible. * It then makes the ToolTip visible, which triggers * the ToolTipManager's showEffect if one is specified. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function showTip():void { // Dispatch a ""showToolTip"" event // from the object displaying the tooltip. var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_SHOW); event.toolTip = currentToolTip; currentTarget.dispatchEvent(event); if (isError) { // Listen for a change event so we know when to hide the tip currentTarget.addEventListener(Event.CHANGE, changeHandler); } else { var sm:ISystemManager = getSystemManager(currentTarget); sm.addEventListener(MouseEvent.MOUSE_DOWN, systemManager_mouseDownHandler); } // Make the tooltip visible. // If showEffect exists, this effect will play. // When the effect ends, effectEndHandler() // will start the hideTimer. currentToolTip.visible = true; if (!showEffect) showEffectEnded(); } /** * Hides the current ToolTip. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function hideTip():void { // Dispatch a ""hideToolTip"" event // from the object that was displaying the tooltip. if (previousTarget) { var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_HIDE); event.toolTip = currentToolTip; previousTarget.dispatchEvent(event); } // Make the tooltip invisible. // If hideEffect exists, this effect will play. // When the effect ends, effectEndHandler() // will reset the ToolTipManager to a no-tip state. if (currentToolTip) currentToolTip.visible = false; // When to do this? if (isError) { if (currentTarget) currentTarget.removeEventListener(Event.CHANGE, changeHandler); } else { if (previousTarget) { var sm:ISystemManager = getSystemManager(previousTarget); sm.removeEventListener(MouseEvent.MOUSE_DOWN, systemManager_mouseDownHandler); } } if (!hideEffect) hideEffectEnded(); } /** * Removes any currently visible ToolTip. * If the ToolTip is starting to show or hide, this method * removes the ToolTip immediately without completing the effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function reset():void { // Reset the three timers, in case any are running. showTimer.reset(); hideTimer.reset(); // If there is a current tooltip... if (currentToolTip) { // Remove the event handlers for the effectEnd of the showEffect // and hideEffect, so that calling endEffectsForTarget() doesn't // trigger effectEndHandler(). if (showEffect || hideEffect) { currentToolTip.removeEventListener(EffectEvent.EFFECT_END, effectEndHandler); } // End any show or hide effects that might be playing on it. EffectManager.endEffectsForTarget(currentToolTip); var e:DynamicEvent; if (hasEventListener(""removeChild"")) { e = new DynamicEvent(""removeChild"", false, true); e.sm = currentToolTip.systemManager; e.toolTip = currentToolTip; } if (!e || dispatchEvent(e)) { // Remove it. var sm:ISystemManager = currentToolTip.systemManager as ISystemManager; sm.topLevelSystemManager.toolTipChildren.removeChild(currentToolTip as DisplayObject); } currentToolTip = null; scrubTimer.delay = scrubDelay; scrubTimer.reset(); if (scrubDelay > 0) { scrubTimer.delay = scrubDelay; scrubTimer.start(); } } } /** * Creates an instance of the ToolTip class with the specified text * and displays it at the specified location in stage coordinates. * *

ToolTips appear in their own layer, on top of everything * except cursors.

* *

The standard way of using ToolTips is to let the ToolTipManager * automatically show and hide them as the user moves the mouse over * the objects that have the toolTip property set. * You can turn off this automatic ToolTip management by setting * the ToolTipManager's enabled property to * false.

* *

By contrast, this method—along with hideToolTip()—gives * you programmatic control over ToolTips. * You can show them when and where you choose, * and you can even show more than one at once if you need to. * (The ToolTipManager never does this, because it is generally * confusing to the user).

* *

This method first creates a new instance of ToolTip and calls the * addChild() method to put it into the SystemManager's * toolTips layer. * If you are showing an error tip, it sets the appropriate styles. * Then it sets the text for the ToolTip, sizes the ToolTip based on * its text, and positions it where you specified.

* *

You must save the reference to the ToolTip that this method * returns so that you can pass it to the hideToolTip() method.

* * @param text The text to display in the ToolTip instance. * * @param x The horizontal coordinate of the ToolTip in stage coordinates. * In case of multiple stages, the relevant stage is determined * from the context argument. * * @param y The vertical coordinate of the ToolTip in stage coordinates. * In case of multiple stages, the relevant stage is determined * from the context argument. * * @param errorTipBorderStyle The border style of an error tip. This method * argument can be null, ""errorTipRight"", ""errorTipAbove"", or ""errorTipBelow"". * If it is null, then the createToolTip() method creates a normal ToolTip. If it is * ""errorTipRight"", ""errorTipAbove"", or ""errorTipBelow"", then the createToolTip() * method creates an error tip, and this parameter determines where the arrow * of the error tip points to (the error's target). For example, if you pass ""errorTipRight"", Flex * positions the error tip (via the x and y arguments) to the * right of the error target; the arrow is on the left edge of the error tip. * * @param context This property is not currently used. * * @return The newly created ToolTip. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function createToolTip(text:String, x:Number, y:Number, errorTipBorderStyle:String = null, context:IUIComponent = null):IToolTip { var toolTip:ToolTip = new ToolTip(); var sm:ISystemManager = context ? context.systemManager as ISystemManager: FlexGlobals.topLevelApplication.systemManager as ISystemManager; if (context is IFlexModule) toolTip.moduleFactory = IFlexModule(context).moduleFactory; else toolTip.moduleFactory = sm; var e:DynamicEvent; if (hasEventListener(""addChild"")) { e = new DynamicEvent(""addChild"", false, true); e.sm = sm; e.toolTip = toolTip; } if (!e || dispatchEvent(e)) { sm.topLevelSystemManager.toolTipChildren.addChild(toolTip as DisplayObject); } if (errorTipBorderStyle) { toolTip.setStyle(""styleName"", ""errorTip""); toolTip.setStyle(""borderStyle"", errorTipBorderStyle); } toolTip.text = text; sizeTip(toolTip); toolTip.move(x, y); // Ensure that tip is on screen? // Should x and y for error tip be tip of pointy border? // show effect? return toolTip as IToolTip; } /** * Destroys a specified ToolTip that was created by the createToolTip() method. * *

This method calls the removeChild() method to remove the specified * ToolTip from the SystemManager's ToolTips layer. * It will then be garbage-collected unless you keep a * reference to it.

* *

You should not call this method on the ToolTipManager's * currentToolTip.

* * @param toolTip The ToolTip instance to destroy. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function destroyToolTip(toolTip:IToolTip):void { var e:DynamicEvent; if (hasEventListener(""removeChild"")) { e = new DynamicEvent(""removeChild"", false, true); e.sm = toolTip.systemManager; e.toolTip = toolTip; } if (!e || dispatchEvent(e)) { // Remove it. var sm:ISystemManager = toolTip.systemManager as ISystemManager; sm.topLevelSystemManager.toolTipChildren.removeChild(toolTip as DisplayObject); } // hide effect? } /** * @private */ mx_internal function showEffectEnded():void { if (hideDelay == 0) { hideTip(); } else if (hideDelay < Infinity) { hideTimer.delay = hideDelay; hideTimer.start(); } if (currentTarget) { // Dispatch a ""toolTipShown"" event // from the object displaying the tooltip. var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_SHOWN); event.toolTip = currentToolTip; currentTarget.dispatchEvent(event); } } /** * @private */ mx_internal function hideEffectEnded():void { reset(); // Dispatch a ""toolTipEnd"" event // from the object that was displaying the tooltip. if (previousTarget) { var event:ToolTipEvent = new ToolTipEvent(ToolTipEvent.TOOL_TIP_END); event.toolTip = currentToolTip; previousTarget.dispatchEvent(event); } } /** * @private */ mx_internal function getSystemManager( target:DisplayObject):ISystemManager { return target is IUIComponent ? IUIComponent(target).systemManager : null; } /** * @private */ private function getGlobalBounds(obj:DisplayObject, parent:DisplayObject, mirror:Boolean):Rectangle { var upperLeft:Point = new Point(0, 0); upperLeft = obj.localToGlobal(upperLeft); // If the layout has been mirrored, then the 0,0 is the uppper // right corner; compensate here. if (mirror) upperLeft.x -= obj.width; upperLeft = parent.globalToLocal(upperLeft); return new Rectangle(upperLeft.x, upperLeft.y, obj.width, obj.height); } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private * This handler is called when the mouse moves over an object * with a toolTip. */ mx_internal function toolTipMouseOverHandler(event:MouseEvent):void { checkIfTargetChanged(DisplayObject(event.target)); } /** * @private * This handler is called when the mouse moves out of an object * with a toolTip. */ mx_internal function toolTipMouseOutHandler(event:MouseEvent):void { checkIfTargetChanged(event.relatedObject); } /** * @private * This handler is called when the mouse moves over an object * with an errorString. */ mx_internal function errorTipMouseOverHandler(event:MouseEvent):void { checkIfTargetChanged(DisplayObject(event.target)); } /** * @private * This handler is called when the mouse moves out of an object * with an errorString. */ mx_internal function errorTipMouseOutHandler(event:MouseEvent):void { checkIfTargetChanged(event.relatedObject); } /** * @private * This handler is called when the showTimer fires. * It creates the tooltip and starts its showEffect. */ mx_internal function showTimer_timerHandler(event:TimerEvent):void { // Make sure we still have a currentTarget when the timer fires. if (currentTarget) { createTip(); initializeTip(); positionTip(); showTip(); } } /** * @private * This handler is called when the hideTimer fires. * It starts the hideEffect. */ mx_internal function hideTimer_timerHandler(event:TimerEvent):void { hideTip(); } /** * @private * This handler is called when the showEffect or hideEffect ends. * When the showEffect ends, it starts the hideTimer, * which will automatically start hiding the tooltip when it fires, * even if the mouse is still over the target. * When the hideEffect ends, the tooltip is removed. */ mx_internal function effectEndHandler(event:EffectEvent):void { if (event.effectInstance.effect == showEffect) showEffectEnded(); else if (event.effectInstance.effect == hideEffect) hideEffectEnded(); } /** * @private * This handler is called when the user clicks the mouse * while a normal tooltip is displayed. * It immediately hides the tooltip. */ mx_internal function systemManager_mouseDownHandler(event:MouseEvent):void { reset(); } /** * @private */ mx_internal function changeHandler(event:Event):void { reset(); } } } ",12147,False,2486.4915745909952,median "// Urho3D editor hierarchy window handling const int ITEM_NONE = 0; const int ITEM_NODE = 1; const int ITEM_COMPONENT = 2; const int ITEM_UI_ELEMENT = 3; const uint NO_ITEM = M_MAX_UNSIGNED; const StringHash SCENE_TYPE(""Scene""); const StringHash NODE_TYPE(""Node""); const StringHash STATICMODEL_TYPE(""StaticModel""); const StringHash ANIMATEDMODEL_TYPE(""AnimatedModel""); const StringHash STATICMODELGROUP_TYPE(""StaticModelGroup""); const StringHash SPLINEPATH_TYPE(""SplinePath""); const StringHash CONSTRAINT_TYPE(""Constraint""); const String NO_CHANGE(uint8(0)); const StringHash TYPE_VAR(""Type""); const StringHash NODE_ID_VAR(""NodeID""); const StringHash COMPONENT_ID_VAR(""ComponentID""); const StringHash UI_ELEMENT_ID_VAR(""UIElementID""); const StringHash DRAGDROPCONTENT_VAR(""DragDropContent""); const StringHash[] ID_VARS = { StringHash(""""), NODE_ID_VAR, COMPONENT_ID_VAR, UI_ELEMENT_ID_VAR }; Color nodeTextColor(1.0f, 1.0f, 1.0f); Color componentTextColor(0.7f, 1.0f, 0.7f); Window@ hierarchyWindow; ListView@ hierarchyList; bool showID = true; // UIElement does not have unique ID, so use a running number to generate a new ID each time an item is inserted into hierarchy list const uint UI_ELEMENT_BASE_ID = 1; uint uiElementNextID = UI_ELEMENT_BASE_ID; bool showInternalUIElement = false; bool showTemporaryObject = false; Array hierarchyUpdateSelections; Variant GetUIElementID(UIElement@ element) { Variant elementID = element.GetVar(UI_ELEMENT_ID_VAR); if (elementID.empty) { // Generate new ID elementID = uiElementNextID++; // Store the generated ID element.vars[UI_ELEMENT_ID_VAR] = elementID; } return elementID; } UIElement@ GetUIElementByID(const Variant&in id) { return id == UI_ELEMENT_BASE_ID ? editorUIElement : editorUIElement.GetChild(UI_ELEMENT_ID_VAR, id, true); } void CreateHierarchyWindow() { if (hierarchyWindow !is null) return; hierarchyWindow = LoadEditorUI(""UI/EditorHierarchyWindow.xml""); hierarchyList = hierarchyWindow.GetChild(""HierarchyList""); ui.root.AddChild(hierarchyWindow); int height = Min(ui.root.height - 60, 500); hierarchyWindow.SetSize(300, height); hierarchyWindow.SetPosition(35, 100); hierarchyWindow.opacity = uiMaxOpacity; hierarchyWindow.BringToFront(); UpdateHierarchyItem(editorScene); // Set selection to happen on click end, so that we can drag nodes to the inspector without resetting the inspector view hierarchyList.selectOnClickEnd = true; // Set drag & drop target mode on the node list background, which is used to parent nodes back to the root node hierarchyList.contentElement.dragDropMode = DD_TARGET; hierarchyList.scrollPanel.dragDropMode = DD_TARGET; SubscribeToEvent(hierarchyWindow.GetChild(""CloseButton"", true), ""Released"", ""HideHierarchyWindow""); SubscribeToEvent(hierarchyWindow.GetChild(""ExpandButton"", true), ""Released"", ""ExpandCollapseHierarchy""); SubscribeToEvent(hierarchyWindow.GetChild(""CollapseButton"", true), ""Released"", ""ExpandCollapseHierarchy""); SubscribeToEvent(hierarchyWindow.GetChild(""ResetButton"", true), ""Released"", ""CollapseHierarchy""); SubscribeToEvent(hierarchyWindow.GetChild(""ShowID"", true), ""Toggled"", ""HandleShowID""); SubscribeToEvent(hierarchyList, ""SelectionChanged"", ""HandleHierarchyListSelectionChange""); SubscribeToEvent(hierarchyList, ""ItemDoubleClicked"", ""HandleHierarchyListDoubleClick""); SubscribeToEvent(hierarchyList, ""ItemClicked"", ""HandleHierarchyItemClick""); SubscribeToEvent(""DragDropTest"", ""HandleDragDropTest""); SubscribeToEvent(""DragDropFinish"", ""HandleDragDropFinish""); SubscribeToEvent(editorScene, ""NodeAdded"", ""HandleNodeAdded""); SubscribeToEvent(editorScene, ""NodeRemoved"", ""HandleNodeRemoved""); SubscribeToEvent(editorScene, ""ComponentAdded"", ""HandleComponentAdded""); SubscribeToEvent(editorScene, ""ComponentRemoved"", ""HandleComponentRemoved""); SubscribeToEvent(editorScene, ""NodeNameChanged"", ""HandleNodeNameChanged""); SubscribeToEvent(editorScene, ""NodeEnabledChanged"", ""HandleNodeEnabledChanged""); SubscribeToEvent(editorScene, ""ComponentEnabledChanged"", ""HandleComponentEnabledChanged""); SubscribeToEvent(""TemporaryChanged"", ""HandleTemporaryChanged""); } bool ToggleHierarchyWindow() { if (hierarchyWindow.visible == false) ShowHierarchyWindow(); else HideHierarchyWindow(); return true; } void ShowHierarchyWindow() { hierarchyWindow.visible = true; hierarchyWindow.BringToFront(); } void HideHierarchyWindow() { hierarchyWindow.visible = false; } void ExpandCollapseHierarchy(StringHash eventType, VariantMap& eventData) { Button@ button = eventData[""Element""].GetPtr(); bool enable = button.name == ""ExpandButton""; CheckBox@ checkBox = hierarchyWindow.GetChild(""AllCheckBox"", true); bool all = checkBox.checked; checkBox.checked = false; // Auto-reset Array selections = hierarchyList.selections; for (uint i = 0; i < selections.length; ++i) hierarchyList.Expand(selections[i], enable, all); } void EnableExpandCollapseButtons(bool enable) { String[] buttons = { ""ExpandButton"", ""CollapseButton"", ""AllCheckBox"" }; for (uint i = 0; i < buttons.length; ++i) { UIElement@ element = hierarchyWindow.GetChild(buttons[i], true); element.enabled = enable; element.children[0].color = enable ? normalTextColor : nonEditableTextColor; } } void UpdateHierarchyItem(Serializable@ serializable, bool clear = false) { if (clear) { // Remove the current selection before updating the list item (in turn trigger an update on the attribute editor) hierarchyList.ClearSelection(); // Clear copybuffer when whole window refreshed sceneCopyBuffer.Clear(); uiElementCopyBuffer.Clear(); } // In case of item's parent is not found in the hierarchy list then the item will be inserted at the list root level Serializable@ parent; switch (GetType(serializable)) { case ITEM_NODE: parent = cast(serializable).parent; break; case ITEM_COMPONENT: parent = cast(serializable).node; break; case ITEM_UI_ELEMENT: parent = cast(serializable).parent; break; default: break; } UIElement@ parentItem = hierarchyList.items[GetListIndex(parent)]; UpdateHierarchyItem(GetListIndex(serializable), serializable, parentItem); } uint UpdateHierarchyItem(uint itemIndex, Serializable@ serializable, UIElement@ parentItem) { // Whenever we're updating, disable layout update to optimize speed hierarchyList.contentElement.DisableLayoutUpdate(); if (serializable is null) { hierarchyList.RemoveItem(itemIndex); hierarchyList.contentElement.EnableLayoutUpdate(); hierarchyList.contentElement.UpdateLayout(); return itemIndex; } int itemType = GetType(serializable); Variant id = GetID(serializable, itemType); // Remove old item if exists if (itemIndex < hierarchyList.numItems && MatchID(hierarchyList.items[itemIndex], id, itemType)) hierarchyList.RemoveItem(itemIndex); Text@ text = Text(); hierarchyList.InsertItem(itemIndex, text, parentItem); text.style = ""FileSelectorListText""; if (serializable.type == SCENE_TYPE || serializable is editorUIElement) // The root node (scene) and editor's root UIElement cannot be moved by drag and drop text.dragDropMode = DD_TARGET; else // Internal UIElement is not able to participate in drag and drop action text.dragDropMode = itemType == ITEM_UI_ELEMENT && cast(serializable).internal ? DD_DISABLED : DD_SOURCE_AND_TARGET; // Advance the index for the child items if (itemIndex == M_MAX_UNSIGNED) itemIndex = hierarchyList.numItems; else ++itemIndex; String iconType = serializable.typeName; if (serializable is editorUIElement) iconType = ""Root"" + iconType; IconizeUIElement(text, iconType); SetID(text, serializable, itemType); switch (itemType) { case ITEM_NODE: { Node@ node = cast(serializable); text.text = GetNodeTitle(node); text.color = nodeTextColor; SetIconEnabledColor(text, node.enabled); // Update components first for (uint i = 0; i < node.numComponents; ++i) { Component@ component = node.components[i]; if (showTemporaryObject || !component.temporary) AddComponentItem(itemIndex++, component, text); } // Then update child nodes recursively for (uint i = 0; i < node.numChildren; ++i) { Node@ childNode = node.children[i]; if (showTemporaryObject || !childNode.temporary) itemIndex = UpdateHierarchyItem(itemIndex, childNode, text); } break; } case ITEM_COMPONENT: { Component@ component = cast(serializable); text.text = GetComponentTitle(component); text.color = componentTextColor; SetIconEnabledColor(text, component.enabledEffective); break; } case ITEM_UI_ELEMENT: { UIElement@ element = cast(serializable); text.text = GetUIElementTitle(element); SetIconEnabledColor(text, element.visible); // Update child elements recursively for (uint i = 0; i < element.numChildren; ++i) { UIElement@ childElement = element.children[i]; if ((showInternalUIElement || !childElement.internal) && (showTemporaryObject || !childElement.temporary)) itemIndex = UpdateHierarchyItem(itemIndex, childElement, text); } break; } default: break; } // Re-enable layout update (and do manual layout) now hierarchyList.contentElement.EnableLayoutUpdate(); hierarchyList.contentElement.UpdateLayout(); return itemIndex; } void UpdateHierarchyItemText(uint itemIndex, bool iconEnabled, const String&in textTitle = NO_CHANGE) { Text@ text = hierarchyList.items[itemIndex]; if (text is null) return; SetIconEnabledColor(text, iconEnabled); if (textTitle != NO_CHANGE) text.text = textTitle; } void AddComponentItem(uint compItemIndex, Component@ component, UIElement@ parentItem) { Text@ text = Text(); hierarchyList.InsertItem(compItemIndex, text, parentItem); text.style = ""FileSelectorListText""; text.vars[TYPE_VAR] = ITEM_COMPONENT; text.vars[NODE_ID_VAR] = component.node.id; text.vars[COMPONENT_ID_VAR] = component.id; text.text = GetComponentTitle(component); text.color = componentTextColor; // Components currently act only as drag targets text.dragDropMode = DD_TARGET; IconizeUIElement(text, component.typeName); SetIconEnabledColor(text, component.enabledEffective); } int GetType(Serializable@ serializable) { if (cast(serializable) !is null) return ITEM_NODE; else if (cast(serializable) !is null) return ITEM_COMPONENT; else if (cast(serializable) !is null) return ITEM_UI_ELEMENT; else return ITEM_NONE; } void SetID(Text@ text, Serializable@ serializable, int itemType = ITEM_NONE) { // If item type is not provided, auto detect it if (itemType == ITEM_NONE) itemType = GetType(serializable); text.vars[TYPE_VAR] = itemType; text.vars[ID_VARS[itemType]] = GetID(serializable, itemType); // Set node ID as drag and drop content for node ID editing if (itemType == ITEM_NODE) text.vars[DRAGDROPCONTENT_VAR] = String(text.vars[NODE_ID_VAR].GetUInt()); switch (itemType) { case ITEM_COMPONENT: text.vars[NODE_ID_VAR] = cast(serializable).node.id; break; case ITEM_UI_ELEMENT: // Subscribe to UI-element events SubscribeToEvent(serializable, ""NameChanged"", ""HandleElementNameChanged""); SubscribeToEvent(serializable, ""VisibleChanged"", ""HandleElementVisibilityChanged""); SubscribeToEvent(serializable, ""Resized"", ""HandleElementAttributeChanged""); SubscribeToEvent(serializable, ""Positioned"", ""HandleElementAttributeChanged""); break; default: break; } } uint GetID(Serializable@ serializable, int itemType = ITEM_NONE) { // If item type is not provided, auto detect it if (itemType == ITEM_NONE) itemType = GetType(serializable); switch (itemType) { case ITEM_NODE: return cast(serializable).id; case ITEM_COMPONENT: return cast(serializable).id; case ITEM_UI_ELEMENT: return GetUIElementID(cast(serializable)).GetUInt(); } return M_MAX_UNSIGNED; } bool MatchID(UIElement@ element, const Variant&in id, int itemType) { return element.GetVar(TYPE_VAR).GetInt() == itemType && element.GetVar(ID_VARS[itemType]) == id; } uint GetListIndex(Serializable@ serializable) { if (serializable is null) return NO_ITEM; int itemType = GetType(serializable); Variant id = GetID(serializable, itemType); uint numItems = hierarchyList.numItems; for (uint i = 0; i < numItems; ++i) { if (MatchID(hierarchyList.items[i], id, itemType)) return i; } return NO_ITEM; } UIElement@ GetListUIElement(uint index) { UIElement@ item = hierarchyList.items[index]; if (item is null) return null; // Get the text item's ID and use it to retrieve the actual UIElement the text item is associated to return GetUIElementByID(GetUIElementID(item)); } Node@ GetListNode(uint index) { UIElement@ item = hierarchyList.items[index]; if (item is null) return null; return editorScene.GetNode(item.vars[NODE_ID_VAR].GetUInt()); } Component@ GetListComponent(uint index) { UIElement@ item = hierarchyList.items[index]; return GetListComponent(item); } Component@ GetListComponent(UIElement@ item) { if (item is null) return null; if (item.vars[TYPE_VAR].GetInt() != ITEM_COMPONENT) return null; return editorScene.GetComponent(item.vars[COMPONENT_ID_VAR].GetUInt()); } uint GetComponentListIndex(Component@ component) { if (component is null) return NO_ITEM; uint numItems = hierarchyList.numItems; for (uint i = 0; i < numItems; ++i) { UIElement@ item = hierarchyList.items[i]; if (item.vars[TYPE_VAR].GetInt() == ITEM_COMPONENT && item.vars[COMPONENT_ID_VAR].GetUInt() == component.id) return i; } return NO_ITEM; } String GetUIElementTitle(UIElement@ element) { String ret; // Only top level UI-element has this variable String modifiedStr = element.GetVar(MODIFIED_VAR).GetBool() ? ""*"" : """"; ret = (element.name.empty ? element.typeName : element.name) + modifiedStr + "" ["" + GetUIElementID(element).ToString() + ""]""; if (element.temporary) ret += "" (Temp)""; return ret; } String GetNodeTitle(Node@ node) { String ret; if (node.name.empty) ret = node.typeName; else ret = node.name; if (showID) { if (node.id >= FIRST_LOCAL_ID) ret += "" (Local "" + String(node.id) + "")""; else ret += "" ("" + String(node.id) + "")""; if (node.temporary) ret += "" (Temp)""; } return ret; } String GetComponentTitle(Component@ component) { String ret = component.typeName; if (showID) { if (component.id >= FIRST_LOCAL_ID) ret += "" (Local)""; if (component.temporary) ret += "" (Temp)""; } return ret; } void SelectNode(Node@ node, bool multiselect) { if (node is null && !multiselect) { hierarchyList.ClearSelection(); return; } lastSelectedNode = node; uint index = GetListIndex(node); uint numItems = hierarchyList.numItems; if (index < numItems) { // Expand the node chain now if (!multiselect || !hierarchyList.IsSelected(index)) { // Go in the parent chain up to make sure the chain is expanded Node@ current = node; do { hierarchyList.Expand(GetListIndex(current), true); current = current.parent; } while (current !is null); } // This causes an event to be sent, in response we set the node/component selections, and refresh editors if (!multiselect) hierarchyList.selection = index; else hierarchyList.ToggleSelection(index); } else if (!multiselect) hierarchyList.ClearSelection(); } void SelectComponent(Component@ component, bool multiselect) { if (component is null && !multiselect) { hierarchyList.ClearSelection(); return; } Node@ node = component.node; if (node is null && !multiselect) { hierarchyList.ClearSelection(); return; } uint nodeIndex = GetListIndex(node); uint componentIndex = GetComponentListIndex(component); uint numItems = hierarchyList.numItems; if (nodeIndex < numItems && componentIndex < numItems) { // Expand the node chain now if (!multiselect || !hierarchyList.IsSelected(componentIndex)) { // Go in the parent chain up to make sure the chain is expanded Node@ current = node; do { hierarchyList.Expand(GetListIndex(current), true); current = current.parent; } while (current !is null); } // This causes an event to be sent, in response we set the node/component selections, and refresh editors if (!multiselect) hierarchyList.selection = componentIndex; else hierarchyList.ToggleSelection(componentIndex); } else if (!multiselect) hierarchyList.ClearSelection(); } void SelectUIElement(UIElement@ element, bool multiselect) { uint index = GetListIndex(element); uint numItems = hierarchyList.numItems; if (index < numItems) { // Expand the node chain now if (!multiselect || !hierarchyList.IsSelected(index)) { // Go in the parent chain up to make sure the chain is expanded UIElement@ current = element; do { hierarchyList.Expand(GetListIndex(current), true); current = current.parent; } while (current !is null); } if (!multiselect) hierarchyList.selection = index; else hierarchyList.ToggleSelection(index); } else if (!multiselect) hierarchyList.ClearSelection(); } // Find the first selected StaticModel/AtimatedModel component or node with it Model@ FindFirstSelectedModel() { for (uint i = 0; i < selectedComponents.length; ++i) { // Get SM, but also works well for AnimatedModel StaticModel@ sm = cast(selectedComponents[i]); if (sm !is null && sm.model !is null) return sm.model; } for (uint i = 0; i < selectedNodes.length; ++i) { for (uint j = 0; j < selectedNodes[i].numComponents; ++j) { StaticModel@ sm = cast(selectedNodes[i].components[j]); if (sm !is null && sm.model !is null) return sm.model; } } return null; } void UpdateModelInfo(Model@ model) { if (model is null) { modelInfoText.text = """"; return; } String infoStr = ""Model: "" + model.name; infoStr += ""\\n Morphs: "" + model.numMorphs; for (uint g = 0; g < model.numGeometries; ++g) { infoStr += ""\\n Geometry "" + g + ""\\n Lods: "" + model.numGeometryLodLevels[g]; } modelInfoText.text = infoStr; } void HandleHierarchyListSelectionChange() { if (inSelectionModify) return; ClearSceneSelection(); ClearUIElementSelection(); Array indices = hierarchyList.selections; // Enable Expand/Collapse button when there is selection EnableExpandCollapseButtons(indices.length > 0); for (uint i = 0; i < indices.length; ++i) { uint index = indices[i]; UIElement@ item = hierarchyList.items[index]; int type = item.vars[TYPE_VAR].GetInt(); if (type == ITEM_COMPONENT) { Component@ comp = GetListComponent(index); if (comp !is null) selectedComponents.Push(comp); } else if (type == ITEM_NODE) { Node@ node = GetListNode(index); if (node !is null) selectedNodes.Push(node); } else if (type == ITEM_UI_ELEMENT) { UIElement@ element = GetListUIElement(index); if (element !is null && element !is editorUIElement) selectedUIElements.Push(element); } } // If only one node/UIElement selected, use it for editing if (selectedNodes.length == 1) editNode = selectedNodes[0]; if (selectedUIElements.length == 1) editUIElement = selectedUIElements[0]; // If selection contains only components, and they have a common node, use it for editing if (selectedNodes.empty && !selectedComponents.empty) { Node@ commonNode; for (uint i = 0; i < selectedComponents.length; ++i) { if (i == 0) commonNode = selectedComponents[i].node; else { if (selectedComponents[i].node !is commonNode) commonNode = null; } } editNode = commonNode; } UpdateModelInfo(FindFirstSelectedModel()); // Now check if the component(s) can be edited. If many selected, must have same type or have same edit node if (!selectedComponents.empty) { if (editNode is null) { StringHash compType = selectedComponents[0].type; bool sameType = true; for (uint i = 1; i < selectedComponents.length; ++i) { if (selectedComponents[i].type != compType) { sameType = false; break; } } if (sameType) editComponents = selectedComponents; } else { editComponents = selectedComponents; numEditableComponentsPerNode = selectedComponents.length; } } // If just nodes selected, and no components, show as many matching components for editing as possible if (!selectedNodes.empty && selectedComponents.empty && selectedNodes[0].numComponents > 0) { uint count = 0; for (uint j = 0; j < selectedNodes[0].numComponents; ++j) { StringHash compType = selectedNodes[0].components[j].type; bool sameType = true; for (uint i = 1; i < selectedNodes.length; ++i) { if (selectedNodes[i].numComponents <= j || selectedNodes[i].components[j].type != compType) { sameType = false; break; } } if (sameType) { ++count; for (uint i = 0; i < selectedNodes.length; ++i) editComponents.Push(selectedNodes[i].components[j]); } } if (count > 1) numEditableComponentsPerNode = count; } if (selectedNodes.empty && editNode !is null) editNodes.Push(editNode); else { editNodes = selectedNodes; // Cannot multi-edit on scene and node(s) together as scene and node do not share identical attributes, // editing via gizmo does not make too much sense either if (editNodes.length > 1 && editNodes[0] is editorScene) editNodes.Erase(0); } if (selectedUIElements.empty && editUIElement !is null) editUIElements.Push(editUIElement); else editUIElements = selectedUIElements; PositionGizmo(); UpdateAttributeInspector(); UpdateCameraPreview(); } void HandleHierarchyListDoubleClick(StringHash eventType, VariantMap& eventData) { UIElement@ item = eventData[""Item""].GetPtr(); int type = item.vars[TYPE_VAR].GetInt(); // Locate nodes from the scene by double-clicking if (type == ITEM_NODE) { Node@ node = editorScene.GetNode(item.vars[NODE_ID_VAR].GetUInt()); LocateNode(node); } bool isExpanded = hierarchyList.IsExpanded(hierarchyList.selection); if (!isExpanded && eventData[""Button""].GetInt() == MOUSEB_LEFT) { isExpanded = !isExpanded; hierarchyList.Expand(hierarchyList.selection, isExpanded, false); } } void HandleHierarchyItemClick(StringHash eventType, VariantMap& eventData) { if (eventData[""Button""].GetInt() != MOUSEB_RIGHT) return; UIElement@ uiElement = eventData[""Item""].GetPtr(); int selectionIndex = eventData[""Selection""].GetInt(); Array actions; int type = uiElement.vars[TYPE_VAR].GetInt(); // Adds left clicked items to selection which is not normal listview behavior if (type == ITEM_COMPONENT || type == ITEM_NODE) { if (input.keyDown[KEY_LSHIFT]) hierarchyList.AddSelection(selectionIndex); else { hierarchyList.ClearSelection(); hierarchyList.AddSelection(selectionIndex); } } if (type == ITEM_COMPONENT) { Component@ targetComponent = editorScene.GetComponent(uiElement.vars[COMPONENT_ID_VAR].GetUInt()); if (targetComponent is null) return; actions.Push(CreateContextMenuItem(""Copy"", ""HandleHierarchyContextCopy"")); actions.Push(CreateContextMenuItem(""Cut"", ""HandleHierarchyContextCut"")); actions.Push(CreateContextMenuItem(""Delete"", ""HandleHierarchyContextDelete"")); actions.Push(CreateContextMenuItem(""Paste"", ""HandleHierarchyContextPaste"")); actions.Push(CreateContextMenuItem(""Enable/disable"", ""HandleHierarchyContextEnableDisable"")); /* actions.Push(CreateBrowserFileActionMenu(""Edit"", ""HandleBrowserEditResource"", file)); */ } else if (type == ITEM_NODE) { actions.Push(CreateContextMenuItem(""Create Replicated Node"", ""HandleHierarchyContextCreateReplicatedNode"")); actions.Push(CreateContextMenuItem(""Create Local Node"", ""HandleHierarchyContextCreateLocalNode"")); actions.Push(CreateContextMenuItem(""Duplicate"", ""HandleHierarchyContextDuplicate"")); actions.Push(CreateContextMenuItem(""Copy"", ""HandleHierarchyContextCopy"")); actions.Push(CreateContextMenuItem(""Cut"", ""HandleHierarchyContextCut"")); actions.Push(CreateContextMenuItem(""Delete"", ""HandleHierarchyContextDelete"")); actions.Push(CreateContextMenuItem(""Paste"", ""HandleHierarchyContextPaste"")); actions.Push(CreateContextMenuItem(""Reset to default"", ""HandleHierarchyContextResetToDefault"")); actions.Push(CreateContextMenuItem(""Reset position"", ""HandleHierarchyContextResetPosition"")); actions.Push(CreateContextMenuItem(""Reset rotation"", ""HandleHierarchyContextResetRotation"")); actions.Push(CreateContextMenuItem(""Reset scale"", ""HandleHierarchyContextResetScale"")); actions.Push(CreateContextMenuItem(""Enable/disable"", ""HandleHierarchyContextEnableDisable"")); actions.Push(CreateContextMenuItem(""Unparent"", ""HandleHierarchyContextUnparent"")); } else if (type == ITEM_UI_ELEMENT) { // close ui element actions.Push(CreateContextMenuItem(""Close UI-Layout"", ""HandleHierarchyContextUIElementCloseUILayout"")); actions.Push(CreateContextMenuItem(""Close all UI-layouts"", ""HandleHierarchyContextUIElementCloseAllUILayouts"")); } if (actions.length > 0) ActivateContextMenu(actions); } void HandleDragDropTest(StringHash eventType, VariantMap& eventData) { UIElement@ source = eventData[""Source""].GetPtr(); UIElement@ target = eventData[""Target""].GetPtr(); int itemType; eventData[""Accept""] = TestDragDrop(source, target, itemType); } void HandleDragDropFinish(StringHash eventType, VariantMap& eventData) { UIElement@ source = eventData[""Source""].GetPtr(); UIElement@ target = eventData[""Target""].GetPtr(); int itemType = ITEM_NONE; bool accept = TestDragDrop(source, target, itemType); eventData[""Accept""] = accept; if (!accept) return; // resource browser if (source !is null && source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt() > 0) { int type = source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt(); BrowserFile@ browserFile = GetBrowserFileFromId(source.vars[TEXT_VAR_FILE_ID].GetUInt()); if (browserFile is null) return; Component@ createdComponent; if (itemType == ITEM_NODE) { Node@ targetNode = editorScene.GetNode(target.vars[NODE_ID_VAR].GetUInt()); if (targetNode is null) return; if (type == RESOURCE_TYPE_PREFAB) { LoadNode(browserFile.GetFullPath(), targetNode); } else if(type == RESOURCE_TYPE_SCRIPTFILE) { // TODO: not sure what to do here. lots of choices. } else if(type == RESOURCE_TYPE_MODEL) { CreateModelWithStaticModel(browserFile.resourceKey, targetNode); return; } else if (type == RESOURCE_TYPE_PARTICLEEFFECT) { if (browserFile.extension == ""xml"") { ParticleEffect@ effect = cache.GetResource(""ParticleEffect"", browserFile.resourceKey); if (effect is null) return; ParticleEmitter@ emitter = targetNode.CreateComponent(""ParticleEmitter""); emitter.effect = effect; createdComponent = emitter; } } else if (type == RESOURCE_TYPE_2D_PARTICLE_EFFECT) { if (browserFile.extension == ""xml"") { Resource@ effect = cache.GetResource(""ParticleEffect2D"", browserFile.resourceKey); if (effect is null) return; ResourceRef effectRef; effectRef.type = effect.type; effectRef.name = effect.name; Component@ emitter = targetNode.CreateComponent(""ParticleEmitter2D""); emitter.SetAttribute(""Particle Effect"", Variant(effectRef)); createdComponent = emitter; } } } else if (itemType == ITEM_COMPONENT) { Component@ targetComponent = editorScene.GetComponent(target.vars[COMPONENT_ID_VAR].GetUInt()); if (targetComponent is null) return; if (type == RESOURCE_TYPE_MATERIAL) { StaticModel@ model = cast(targetComponent); if (model is null) return; AssignMaterial(model, browserFile.resourceKey); } else if (type == RESOURCE_TYPE_MODEL) { StaticModel@ staticModel = cast(targetComponent); if (staticModel is null) return; AssignModel(staticModel, browserFile.resourceKey); } } else { LineEdit@ text = cast(target); if (text is null) return; text.text = browserFile.resourceKey; VariantMap data(); data[""Element""] = text; data[""Text""] = text.text; text.SendEvent(""TextFinished"", data); } if (createdComponent !is null) { CreateLoadedComponent(createdComponent); } return; } if (itemType == ITEM_NODE) { Node@ targetNode = editorScene.GetNode(target.vars[NODE_ID_VAR].GetUInt()); // If target is null, parent to scene if (targetNode is null) targetNode = editorScene; Array sourceNodes = GetMultipleSourceNodes(source); if (sourceNodes.length > 0) { if (sourceNodes.length > 1) SceneChangeParent(sourceNodes[0], sourceNodes, targetNode); else SceneChangeParent(sourceNodes[0], targetNode); // Focus the node at its new position in the list which in turn should trigger a refresh in attribute inspector FocusNode(sourceNodes[0]); } } else if (itemType == ITEM_UI_ELEMENT) { UIElement@ sourceElement = GetUIElementByID(source.vars[UI_ELEMENT_ID_VAR].GetUInt()); UIElement@ targetElement = GetUIElementByID(target.vars[UI_ELEMENT_ID_VAR].GetUInt()); // If target is null, cannot proceed if (targetElement is null) return; // Perform the reparenting if (!UIElementChangeParent(sourceElement, targetElement)) return; // Focus the element at its new position in the list which in turn should trigger a refresh in attribute inspector FocusUIElement(sourceElement); } else if (itemType == ITEM_COMPONENT) { Array sourceNodes = GetMultipleSourceNodes(source); Component@ targetComponent = editorScene.GetComponent(target.vars[COMPONENT_ID_VAR].GetUInt()); if (targetComponent !is null && sourceNodes.length > 0) { // Drag node to StaticModelGroup to make it an instance StaticModelGroup@ smg = cast(targetComponent); if (smg !is null) { // Save undo action EditAttributeAction action; uint attrIndex = GetAttributeIndex(smg, ""Instance Nodes""); Variant oldIDs = smg.attributes[attrIndex]; for (uint i = 0; i < sourceNodes.length; ++i) smg.AddInstanceNode(sourceNodes[i]); action.Define(smg, attrIndex, oldIDs); SaveEditAction(action); SetSceneModified(); } // Drag node to SplinePath to make it a control point SplinePath@ spline = cast(targetComponent); if (spline !is null) { // Save undo action EditAttributeAction action; uint attrIndex = GetAttributeIndex(spline, ""Control Points""); Variant oldIDs = spline.attributes[attrIndex]; for (uint i = 0; i < sourceNodes.length; ++i) spline.AddControlPoint(sourceNodes[i]); action.Define(spline, attrIndex, oldIDs); SaveEditAction(action); SetSceneModified(); } // Drag a node to Constraint to make it the remote end of the constraint Constraint@ constraint = cast(targetComponent); RigidBody@ rigidBody = sourceNodes[0].GetComponent(""RigidBody""); if (constraint !is null && rigidBody !is null) { // Save undo action EditAttributeAction action; uint attrIndex = GetAttributeIndex(constraint, ""Other Body NodeID""); Variant oldID = constraint.attributes[attrIndex]; constraint.otherBody = rigidBody; action.Define(constraint, attrIndex, oldID); SaveEditAction(action); SetSceneModified(); } } } } Array GetMultipleSourceNodes(UIElement@ source) { Array nodeList; Node@ node = editorScene.GetNode(source.vars[NODE_ID_VAR].GetUInt()); if (node !is null) nodeList.Push(node); // Handle additional selected children from a ListView if (source.parent !is null && source.parent.typeName == ""HierarchyContainer"") { ListView@ listView_ = cast(source.parent.parent.parent); if (listView_ is null) return nodeList; bool sourceIsSelected = false; for (uint i = 0; i < listView_.selectedItems.length; ++i) { if (listView_.selectedItems[i] is source) { sourceIsSelected = true; break; } } if (sourceIsSelected) { for (uint i = 0; i < listView_.selectedItems.length; ++i) { UIElement@ item_ = listView_.selectedItems[i]; // The source item is already added if (item_ is source) continue; if (item_.vars[TYPE_VAR] == ITEM_NODE) { Node@ n = editorScene.GetNode(item_.vars[NODE_ID_VAR].GetUInt()); if (n !is null) nodeList.Push(n); } } } } return nodeList; } bool TestDragDrop(UIElement@ source, UIElement@ target, int& itemType) { int targetItemType = target.GetVar(TYPE_VAR).GetInt(); if (targetItemType == ITEM_NODE) { Node@ sourceNode; Node@ targetNode; Variant variant = source.GetVar(NODE_ID_VAR); if (!variant.empty) sourceNode = editorScene.GetNode(variant.GetUInt()); variant = target.GetVar(NODE_ID_VAR); if (!variant.empty) targetNode = editorScene.GetNode(variant.GetUInt()); if (sourceNode !is null && targetNode !is null) { itemType = ITEM_NODE; if (sourceNode.parent is targetNode) return false; if (targetNode.parent is sourceNode) return false; } // Resource browser if (sourceNode is null && targetNode !is null) { itemType = ITEM_NODE; int type = source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt(); return type == RESOURCE_TYPE_PREFAB || type == RESOURCE_TYPE_SCRIPTFILE || type == RESOURCE_TYPE_MODEL || type == RESOURCE_TYPE_PARTICLEEFFECT || type == RESOURCE_TYPE_2D_PARTICLE_EFFECT; } return true; } else if (targetItemType == ITEM_UI_ELEMENT) { UIElement@ sourceElement; UIElement@ targetElement; Variant variant = source.GetVar(UI_ELEMENT_ID_VAR); if (!variant.empty) sourceElement = GetUIElementByID(variant.GetUInt()); variant = target.GetVar(UI_ELEMENT_ID_VAR); if (!variant.empty) targetElement = GetUIElementByID(variant.GetUInt()); if (sourceElement !is null && targetElement !is null) { itemType = ITEM_UI_ELEMENT; if (sourceElement.parent is targetElement) return false; if (targetElement.parent is sourceElement) return false; } return true; } else if (targetItemType == ITEM_COMPONENT) { // Now only support dragging of nodes to StaticModelGroup, SplinePath or Constraint. Can be expanded to support others Node@ sourceNode; Component@ targetComponent; Variant variant = source.GetVar(NODE_ID_VAR); if (!variant.empty) sourceNode = editorScene.GetNode(variant.GetUInt()); variant = target.GetVar(COMPONENT_ID_VAR); if (!variant.empty) targetComponent = editorScene.GetComponent(variant.GetUInt()); itemType = ITEM_COMPONENT; if (sourceNode !is null && targetComponent !is null && (targetComponent.type == STATICMODELGROUP_TYPE || targetComponent.type == CONSTRAINT_TYPE || targetComponent.type == SPLINEPATH_TYPE)) return true; // resource browser int type = source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt(); if (targetComponent.type == STATICMODEL_TYPE || targetComponent.type == ANIMATEDMODEL_TYPE) return type == RESOURCE_TYPE_MATERIAL || type == RESOURCE_TYPE_MODEL; return false; } else if (source.vars.Contains(TEXT_VAR_RESOURCE_TYPE)) // only testing resource browser ui elements { int type = source.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt(); // test against resource pickers LineEdit@ lineEdit = cast(target); if (lineEdit !is null) { StringHash resourceType = GetResourceTypeFromPickerLineEdit(lineEdit); if (resourceType == StringHash(""Material"") && type == RESOURCE_TYPE_MATERIAL) return true; else if (resourceType == StringHash(""Model"") && type == RESOURCE_TYPE_MODEL) return true; else if (resourceType == StringHash(""Animation"") && type == RESOURCE_TYPE_ANIMATION) return true; } } return true; } StringHash GetResourceTypeFromPickerLineEdit(UIElement@ lineEdit) { Array@ targets = GetAttributeEditorTargets(lineEdit); if (!targets.empty) { resourcePickIndex = lineEdit.vars[""Index""].GetUInt(); resourcePickSubIndex = lineEdit.vars[""SubIndex""].GetUInt(); AttributeInfo info = targets[0].attributeInfos[resourcePickIndex]; StringHash resourceType; if (info.type == VAR_RESOURCEREF) return targets[0].attributes[resourcePickIndex].GetResourceRef().type; else if (info.type == VAR_RESOURCEREFLIST) return targets[0].attributes[resourcePickIndex].GetResourceRefList().type; else if (info.type == VAR_VARIANTVECTOR) return targets[0].attributes[resourcePickIndex].GetVariantVector()[resourcePickSubIndex].GetResourceRef().type; } return StringHash(); } void FocusNode(Node@ node) { uint index = GetListIndex(node); hierarchyList.selection = index; } void FocusComponent(Component@ component) { uint index = GetComponentListIndex(component); hierarchyList.selection = index; } void FocusUIElement(UIElement@ element) { uint index = GetListIndex(element); hierarchyList.selection = index; } void CreateBuiltinObject(const String& name) { Node@ newNode = editorScene.CreateChild(name, REPLICATED); // Set the new node a certain distance from the camera newNode.position = GetNewNodePosition(); StaticModel@ object = newNode.CreateComponent(""StaticModel""); object.model = cache.GetResource(""Model"", ""Models/"" + name + "".mdl""); // Create an undo action for the create CreateNodeAction action; action.Define(newNode); SaveEditAction(action); SetSceneModified(); FocusNode(newNode); } bool CheckHierarchyWindowFocus() { // When we do edit operations based on key shortcuts, make sure the hierarchy list is focused return ui.focusElement is hierarchyList || ui.focusElement is null; } bool CheckForExistingGlobalComponent(Node@ node, const String&in typeName) { if (typeName != ""Octree"" && typeName != ""PhysicsWorld"" && typeName != ""DebugRenderer"") return false; else return node.HasComponent(typeName); } void HandleNodeAdded(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Node@ node = eventData[""Node""].GetPtr(); if (showTemporaryObject || !node.temporary) UpdateHierarchyItem(node); } void HandleNodeRemoved(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Node@ node = eventData[""Node""].GetPtr(); uint index = GetListIndex(node); UpdateHierarchyItem(index, null, null); } void HandleComponentAdded(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; // Insert the newly added component at last component position but before the first child node position of the parent node Node@ node = eventData[""Node""].GetPtr(); Component@ component = eventData[""Component""].GetPtr(); if (showTemporaryObject || !component.temporary) { uint nodeIndex = GetListIndex(node); if (nodeIndex != NO_ITEM) { uint index = node.numChildren > 0 ? GetListIndex(node.children[0]) : M_MAX_UNSIGNED; UpdateHierarchyItem(index, component, hierarchyList.items[nodeIndex]); } } } void HandleComponentRemoved(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Component@ component = eventData[""Component""].GetPtr(); uint index = GetComponentListIndex(component); if (index != NO_ITEM) hierarchyList.RemoveItem(index); } void HandleNodeNameChanged(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Node@ node = eventData[""Node""].GetPtr(); UpdateHierarchyItemText(GetListIndex(node), node.enabled, GetNodeTitle(node)); } void HandleNodeEnabledChanged(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Node@ node = eventData[""Node""].GetPtr(); UpdateHierarchyItemText(GetListIndex(node), node.enabled); attributesDirty = true; } void HandleComponentEnabledChanged(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges) return; Component@ component = eventData[""Component""].GetPtr(); UpdateHierarchyItemText(GetComponentListIndex(component), component.enabledEffective); attributesDirty = true; } void HandleUIElementAdded(StringHash eventType, VariantMap& eventData) { if (suppressUIElementChanges) return; UIElement@ element = eventData[""Element""].GetPtr(); if ((showInternalUIElement || !element.internal) && (showTemporaryObject || !element.temporary)) UpdateHierarchyItem(element); } void HandleUIElementRemoved(StringHash eventType, VariantMap& eventData) { if (suppressUIElementChanges) return; UIElement@ element = eventData[""Element""].GetPtr(); UpdateHierarchyItem(GetListIndex(element), null, null); } void HandleElementNameChanged(StringHash eventType, VariantMap& eventData) { if (suppressUIElementChanges) return; UIElement@ element = eventData[""Element""].GetPtr(); UpdateHierarchyItemText(GetListIndex(element), element.visible, GetUIElementTitle(element)); } void HandleElementVisibilityChanged(StringHash eventType, VariantMap& eventData) { if (suppressUIElementChanges) return; UIElement@ element = eventData[""Element""].GetPtr(); UpdateHierarchyItemText(GetListIndex(element), element.visible); } void HandleElementAttributeChanged(StringHash eventType, VariantMap& eventData) { // Do not refresh the attribute inspector while the attribute is being edited via the attribute-editors if (suppressUIElementChanges || inEditAttribute) return; UIElement@ element = eventData[""Element""].GetPtr(); for (uint i = 0; i < editUIElements.length; ++i) { if (editUIElements[i] is element) attributesDirty = true; } } void HandleTemporaryChanged(StringHash eventType, VariantMap& eventData) { if (suppressSceneChanges || suppressUIElementChanges) return; Serializable@ serializable = cast(GetEventSender()); Node@ node = cast(serializable); if (node !is null && node.scene is editorScene) { if (showTemporaryObject) UpdateHierarchyItemText(GetListIndex(node), node.enabled); else if (!node.temporary && GetListIndex(node) == NO_ITEM) UpdateHierarchyItem(node); else if (node.temporary) UpdateHierarchyItem(GetListIndex(node), null, null); return; } Component@ component = cast(serializable); if (component !is null && component.node !is null && component.node.scene is editorScene) { node = component.node; if (showTemporaryObject) UpdateHierarchyItemText(GetComponentListIndex(component), node.enabled); else if (!component.temporary && GetComponentListIndex(component) == NO_ITEM) { uint nodeIndex = GetListIndex(node); if (nodeIndex != NO_ITEM) { uint index = node.numChildren > 0 ? GetListIndex(node.children[0]) : M_MAX_UNSIGNED; UpdateHierarchyItem(index, component, hierarchyList.items[nodeIndex]); } } else if (component.temporary) { uint index = GetComponentListIndex(component); if (index != NO_ITEM) hierarchyList.RemoveItem(index); } return; } UIElement@ element = cast(serializable); if (element !is null) { if (showTemporaryObject) UpdateHierarchyItemText(GetListIndex(element), element.visible); else if (!element.temporary && GetListIndex(element) == NO_ITEM) UpdateHierarchyItem(element); else if (element.temporary) UpdateHierarchyItem(GetListIndex(element), null, null); return; } } // Hierarchy window edit functions bool Undo() { if (undoStackPos > 0) { --undoStackPos; // Undo commands in reverse order for (int i = int(undoStack[undoStackPos].actions.length - 1); i >= 0; --i) undoStack[undoStackPos].actions[i].Undo(); } return true; } bool Redo() { if (undoStackPos < undoStack.length) { // Redo commands in same order as stored for (uint i = 0; i < undoStack[undoStackPos].actions.length; ++i) undoStack[undoStackPos].actions[i].Redo(); ++undoStackPos; } return true; } bool Cut() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && SceneCut(); // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementCut(); return ret; } return false; } bool Duplicate() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && (selectedNodes.empty || selectedComponents.empty ? SceneDuplicate() : false); // Node and component is mutually exclusive for copy action // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementDuplicate(); return ret; } return false; } bool Copy() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && (selectedNodes.empty || selectedComponents.empty ? SceneCopy() : false); // Node and component is mutually exclusive for copy action // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementCopy(); return ret; } return false; } bool Paste() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (editNode !is null && !sceneCopyBuffer.empty) ret = ret && ScenePaste(); // Not mutually exclusive if (editUIElement !is null && !uiElementCopyBuffer.empty) ret = ret && UIElementPaste(); return ret; } return false; } bool BlenderModeDelete() { if (ui.focusElement is null) { Array actions; actions.Push(CreateContextMenuItem(""Delete?"", ""HandleBlenderModeDelete"")); actions.Push(CreateContextMenuItem(""Cancel"", ""HandleEmpty"")); if (actions.length > 0) { ActivateContextMenu(actions); return true; } } return false; } bool Delete() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && SceneDelete(); // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementDelete(); return ret; } return false; } bool SelectAll() { if (CheckHierarchyWindowFocus()) { if (!selectedNodes.empty || !selectedComponents.empty) return SceneSelectAll(); else if (!selectedUIElements.empty || hierarchyList.items[GetListIndex(editorUIElement)].selected) return UIElementSelectAll(); else return SceneSelectAll(); // If nothing is selected yet, fall back to scene select all } return false; } bool DeselectAll() { if (CheckHierarchyWindowFocus()) { BeginSelectionModify(); hierarchyList.ClearSelection(); EndSelectionModify(); return true; } return false; } bool ResetToDefault() { if (CheckHierarchyWindowFocus()) { bool ret = true; if (!selectedNodes.empty || !selectedComponents.empty) ret = ret && (selectedNodes.empty || selectedComponents.empty ? SceneResetToDefault() : false); // Node and component is mutually exclusive for reset-to-default action // Not mutually exclusive if (!selectedUIElements.empty) ret = ret && UIElementResetToDefault(); return ret; } return false; } void ClearEditActions() { undoStack.Clear(); undoStackPos = 0; } void SaveEditAction(EditAction@ action) { // Create a group with 1 action EditActionGroup group; group.actions.Push(action); SaveEditActionGroup(group); } void SaveEditActionGroup(EditActionGroup@ group) { if (group.actions.empty) return; // Truncate the stack first to current pos undoStack.Resize(undoStackPos); undoStack.Push(group); ++undoStackPos; // Limit maximum undo steps if (undoStack.length > MAX_UNDOSTACK_SIZE) { undoStack.Erase(0); --undoStackPos; } } void BeginSelectionModify() { // A large operation on selected nodes is about to begin. Disable intermediate selection updates inSelectionModify = true; // Cursor shape reverts back to normal automatically after the large operation is completed ui.cursor.shape = CS_BUSY; } void EndSelectionModify() { // The large operation on selected nodes has ended. Update node/component selection now inSelectionModify = false; HandleHierarchyListSelectionChange(); } void HandleHierarchyContextCreateReplicatedNode() { CreateNode(REPLICATED); } void HandleHierarchyContextCreateLocalNode() { CreateNode(LOCAL); } void HandleHierarchyContextDuplicate() { Duplicate(); } void HandleHierarchyContextCopy() { Copy(); } void HandleHierarchyContextCut() { Cut(); } void HandleHierarchyContextDelete() { Delete(); } void HandleBlenderModeDelete() { Delete(); } void HandleEmpty() { //just doing nothing } void HandleHierarchyContextPaste() { Paste(); } void HandleHierarchyContextResetToDefault() { ResetToDefault(); } void HandleHierarchyContextResetPosition() { SceneResetPosition(); } void HandleHierarchyContextResetRotation() { SceneResetRotation(); } void HandleHierarchyContextResetScale() { SceneResetScale(); } void HandleHierarchyContextEnableDisable() { SceneToggleEnable(); } void HandleHierarchyContextUnparent() { SceneUnparent(); } void HandleHierarchyContextUIElementCloseUILayout() { CloseUILayout(); } void HandleHierarchyContextUIElementCloseAllUILayouts() { CloseAllUILayouts(); } void CollapseHierarchy() { Array oldSelections = hierarchyList.selections; Array selections = {0}; hierarchyList.SetSelections(selections); for (uint i = 0; i < selections.length; ++i) hierarchyList.Expand(selections[i], false, true); // only scene's scope expand by default hierarchyList.Expand(0, true, false); hierarchyList.SetSelections(oldSelections); } void CollapseHierarchy(StringHash eventType, VariantMap& eventData) { CollapseHierarchy(); } void HandleShowID(StringHash eventType, VariantMap& eventData) { CheckBox@ checkBox = eventData[""Element""].GetPtr(); showID = checkBox.checked; UpdateHierarchyItem(editorScene, false); CollapseHierarchy(); } ",12247,False,2294.995540681908,median "-- Basic intuitionistic modal logic S4, without ∨, ⊥, or ◇. -- Translation between different formalisations of syntax. module BasicIS4.Syntax.Translation where open import BasicIS4.Syntax.Common public import BasicIS4.Syntax.ClosedHilbertSequential as CHS import BasicIS4.Syntax.ClosedHilbert as CH import BasicIS4.Syntax.HilbertSequential as HS import BasicIS4.Syntax.Hilbert as H import BasicIS4.Syntax.Gentzen as G import BasicIS4.Syntax.DyadicHilbertSequential as DHS import BasicIS4.Syntax.DyadicHilbert as DH import BasicIS4.Syntax.DyadicGentzen as DG import BasicIS4.Syntax.LabelledGentzen as LG open HS using () renaming (_⊦⊢_ to HS⟨_⊦⊢_⟩ ; _⊢_ to HS⟨_⊢_⟩) public open H using () renaming (_⊢_ to H⟨_⊢_⟩ ; _⊢⋆_ to H⟨_⊢⋆_⟩) public open G using () renaming (_⊢_ to G⟨_⊢_⟩ ; _⊢⋆_ to G⟨_⊢⋆_⟩) public open DHS using () renaming (_⊦⊢_ to DHS⟨_⊦⊢_⟩ ; _⊢_ to DHS⟨_⊢_⟩) public open DH using () renaming (_⊢_ to DH⟨_⊢_⟩) public open DG using () renaming (_⊢_ to DG⟨_⊢_⟩ ; _⊢⋆_ to DG⟨_⊢⋆_⟩) public open LG using (_↝_ ; _◎_ ; _◎⋆_) renaming (_⊢_ to LG⟨_⊢_⟩ ; _⊢⋆_ to LG⟨_⊢⋆_⟩) public -- Available translations. -- -- ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ -- │ CHS │ CH │ HS │ H │ G │ DHS │ DH │ DG │ LG │ -- ┌─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ -- │ CHS │ │ d │ d │ ∘ │ ∘ │ ∘ │ ∘ │ ∘ │ ∘ │ -- ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ -- │ CH │ d │ │ ∘ │ d │ ∘ │ ∘ │ ∘ │ ∘ │ ∘ │ -- ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ -- │ HS │ d │ ∘ │ │ d │ ∘ │ d │ ∘ │ ∘ │ ∘ │ -- ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ -- │ H │ ∘ │ d │ d │ │ d │ ∘ │ d │ ∘ │ ∘ │ -- ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ -- │ G │ ∘ │ ∘ │ ∘ │ d │ │ ∘ │ ∘ │ d │ d │ -- ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ -- │ DHS │ ∘ │ ∘ │ d │ ∘ │ ∘ │ │ d │ ∘ │ ∘ │ -- ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ -- │ DH │ ∘ │ ∘ │ ∘ │ d │ ∘ │ d │ │ d │ ∘ │ -- ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ -- │ DG │ ∘ │ ∘ │ ∘ │ ∘ │ ∘! │ ∘ │ d │ │ ∘ │ -- ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ -- │ LG │ ∘ │ ∘ │ ∘ │ WIP │ WIP │ ∘ │ ∘ │ ∘ │ │ -- └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ -- -- d : Direct translation. -- ∘ : Composition of translations. -- ∘! : Composition; direct translation fails the termination check. -- WIP : Work in progress. -- Translation from closed Hilbert-style sequential to closed Hilbert-style. chs→ch : ∀ {A} → CHS.⊢ A → CH.⊢ A chs→ch (Ξ , ts) = chs⊦→ch ts top where chs⊦→ch : ∀ {A Ξ} → CHS.⊦⊢ Ξ → A ∈ Ξ → CH.⊢ A chs⊦→ch (CHS.mp i j ts) top = CH.app (chs⊦→ch ts i) (chs⊦→ch ts j) chs⊦→ch (CHS.ci ts) top = CH.ci chs⊦→ch (CHS.ck ts) top = CH.ck chs⊦→ch (CHS.cs ts) top = CH.cs chs⊦→ch (CHS.nec ss ts) top = CH.box (chs⊦→ch ss top) chs⊦→ch (CHS.cdist ts) top = CH.cdist chs⊦→ch (CHS.cup ts) top = CH.cup chs⊦→ch (CHS.cdown ts) top = CH.cdown chs⊦→ch (CHS.cpair ts) top = CH.cpair chs⊦→ch (CHS.cfst ts) top = CH.cfst chs⊦→ch (CHS.csnd ts) top = CH.csnd chs⊦→ch (CHS.unit ts) top = CH.unit chs⊦→ch (CHS.mp i j ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.ci ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.ck ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.cs ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.nec ss ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.cdist ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.cup ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.cdown ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.cpair ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.cfst ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.csnd ts) (pop k) = chs⊦→ch ts k chs⊦→ch (CHS.unit ts) (pop k) = chs⊦→ch ts k -- Translation from closed Hilbert-style to closed Hilbert-style sequential. ch→chs : ∀ {A} → CH.⊢ A → CHS.⊢ A ch→chs (CH.app t u) = CHS.app (ch→chs t) (ch→chs u) ch→chs CH.ci = ∅ , CHS.ci CHS.nil ch→chs CH.ck = ∅ , CHS.ck CHS.nil ch→chs CH.cs = ∅ , CHS.cs CHS.nil ch→chs (CH.box t) = CHS.box (ch→chs t) ch→chs CH.cdist = ∅ , CHS.cdist CHS.nil ch→chs CH.cup = ∅ , CHS.cup CHS.nil ch→chs CH.cdown = ∅ , CHS.cdown CHS.nil ch→chs CH.cpair = ∅ , CHS.cpair CHS.nil ch→chs CH.cfst = ∅ , CHS.cfst CHS.nil ch→chs CH.csnd = ∅ , CHS.csnd CHS.nil ch→chs CH.unit = ∅ , CHS.unit CHS.nil -- Translation from Hilbert-style sequential to Hilbert-style. hs→h : ∀ {A Γ} → HS⟨ Γ ⊢ A ⟩ → H⟨ Γ ⊢ A ⟩ hs→h (Ξ , ts) = hs⊦→h ts top where hs⊦→h : ∀ {A Ξ Γ} → HS⟨ Γ ⊦⊢ Ξ ⟩ → A ∈ Ξ → H⟨ Γ ⊢ A ⟩ hs⊦→h (HS.var i ts) top = H.var i hs⊦→h (HS.mp i j ts) top = H.app (hs⊦→h ts i) (hs⊦→h ts j) hs⊦→h (HS.ci ts) top = H.ci hs⊦→h (HS.ck ts) top = H.ck hs⊦→h (HS.cs ts) top = H.cs hs⊦→h (HS.nec ss ts) top = H.box (hs⊦→h ss top) hs⊦→h (HS.cdist ts) top = H.cdist hs⊦→h (HS.cup ts) top = H.cup hs⊦→h (HS.cdown ts) top = H.cdown hs⊦→h (HS.cpair ts) top = H.cpair hs⊦→h (HS.cfst ts) top = H.cfst hs⊦→h (HS.csnd ts) top = H.csnd hs⊦→h (HS.unit ts) top = H.unit hs⊦→h (HS.var i ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.mp i j ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.ci ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.ck ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.cs ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.nec ss ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.cdist ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.cup ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.cdown ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.cpair ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.cfst ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.csnd ts) (pop k) = hs⊦→h ts k hs⊦→h (HS.unit ts) (pop k) = hs⊦→h ts k -- Translation from Hilbert-style to Hilbert-style sequential. h→hs : ∀ {A Γ} → H⟨ Γ ⊢ A ⟩ → HS⟨ Γ ⊢ A ⟩ h→hs (H.var i) = ∅ , HS.var i HS.nil h→hs (H.app t u) = HS.app (h→hs t) (h→hs u) h→hs H.ci = ∅ , HS.ci HS.nil h→hs H.ck = ∅ , HS.ck HS.nil h→hs H.cs = ∅ , HS.cs HS.nil h→hs (H.box t) = HS.box (h→hs t) h→hs H.cdist = ∅ , HS.cdist HS.nil h→hs H.cup = ∅ , HS.cup HS.nil h→hs H.cdown = ∅ , HS.cdown HS.nil h→hs H.cpair = ∅ , HS.cpair HS.nil h→hs H.cfst = ∅ , HS.cfst HS.nil h→hs H.csnd = ∅ , HS.csnd HS.nil h→hs H.unit = ∅ , HS.unit HS.nil -- Translation from dyadic Hilbert-style sequential to dyadic Hilbert-style. dhs→dh : ∀ {A Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → DH⟨ Γ ⁏ Δ ⊢ A ⟩ dhs→dh (Ξ , ts) = dhs⊦→dh ts top where dhs⊦→dh : ∀ {A Ξ Γ Δ} → DHS⟨ Γ ⁏ Δ ⊦⊢ Ξ ⟩ → A ∈ Ξ → DH⟨ Γ ⁏ Δ ⊢ A ⟩ dhs⊦→dh (DHS.var i ts) top = DH.var i dhs⊦→dh (DHS.mp i j ts) top = DH.app (dhs⊦→dh ts i) (dhs⊦→dh ts j) dhs⊦→dh (DHS.ci ts) top = DH.ci dhs⊦→dh (DHS.ck ts) top = DH.ck dhs⊦→dh (DHS.cs ts) top = DH.cs dhs⊦→dh (DHS.mvar i ts) top = DH.mvar i dhs⊦→dh (DHS.nec ss ts) top = DH.box (dhs⊦→dh ss top) dhs⊦→dh (DHS.cdist ts) top = DH.cdist dhs⊦→dh (DHS.cup ts) top = DH.cup dhs⊦→dh (DHS.cdown ts) top = DH.cdown dhs⊦→dh (DHS.cpair ts) top = DH.cpair dhs⊦→dh (DHS.cfst ts) top = DH.cfst dhs⊦→dh (DHS.csnd ts) top = DH.csnd dhs⊦→dh (DHS.unit ts) top = DH.unit dhs⊦→dh (DHS.var i ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.mp i j ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.ci ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.ck ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.cs ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.mvar i ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.nec ss ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.cdist ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.cup ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.cdown ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.cpair ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.cfst ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.csnd ts) (pop k) = dhs⊦→dh ts k dhs⊦→dh (DHS.unit ts) (pop k) = dhs⊦→dh ts k -- Translation from dyadic Hilbert-style to dyadic Hilbert-style sequential dh→dhs : ∀ {A Γ Δ} → DH⟨ Γ ⁏ Δ ⊢ A ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ dh→dhs (DH.var i) = ∅ , DHS.var i DHS.nil dh→dhs (DH.app t u) = DHS.app (dh→dhs t) (dh→dhs u) dh→dhs DH.ci = ∅ , DHS.ci DHS.nil dh→dhs DH.ck = ∅ , DHS.ck DHS.nil dh→dhs DH.cs = ∅ , DHS.cs DHS.nil dh→dhs (DH.mvar i) = ∅ , DHS.mvar i DHS.nil dh→dhs (DH.box t) = DHS.box (dh→dhs t) dh→dhs DH.cdist = ∅ , DHS.cdist DHS.nil dh→dhs DH.cup = ∅ , DHS.cup DHS.nil dh→dhs DH.cdown = ∅ , DHS.cdown DHS.nil dh→dhs DH.cpair = ∅ , DHS.cpair DHS.nil dh→dhs DH.cfst = ∅ , DHS.cfst DHS.nil dh→dhs DH.csnd = ∅ , DHS.csnd DHS.nil dh→dhs DH.unit = ∅ , DHS.unit DHS.nil -- Deduction and detachment theorems for Hilbert-style sequential. hs-lam : ∀ {A B Γ} → HS⟨ Γ , A ⊢ B ⟩ → HS⟨ Γ ⊢ A ▻ B ⟩ hs-lam = h→hs ∘ H.lam ∘ hs→h hs-lam⋆₀ : ∀ {A Γ} → HS⟨ Γ ⊢ A ⟩ → HS⟨ ∅ ⊢ Γ ▻⋯▻ A ⟩ hs-lam⋆₀ = h→hs ∘ H.lam⋆₀ ∘ hs→h hs-det : ∀ {A B Γ} → HS⟨ Γ ⊢ A ▻ B ⟩ → HS⟨ Γ , A ⊢ B ⟩ hs-det = h→hs ∘ H.det ∘ hs→h hs-det⋆₀ : ∀ {A Γ} → HS⟨ ∅ ⊢ Γ ▻⋯▻ A ⟩ → HS⟨ Γ ⊢ A ⟩ hs-det⋆₀ = h→hs ∘ H.det⋆₀ ∘ hs→h -- Deduction and detachment theorems for dyadic Hilbert-style sequential. dhs-lam : ∀ {A B Γ Δ} → DHS⟨ Γ , A ⁏ Δ ⊢ B ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ▻ B ⟩ dhs-lam = dh→dhs ∘ DH.lam ∘ dhs→dh dhs-lam⋆₀ : ∀ {A Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → DHS⟨ ∅ ⁏ Δ ⊢ Γ ▻⋯▻ A ⟩ dhs-lam⋆₀ = dh→dhs ∘ DH.lam⋆₀ ∘ dhs→dh dhs-mlam : ∀ {A B Γ Δ} → DHS⟨ Γ ⁏ Δ , A ⊢ B ⟩ → DHS⟨ Γ ⁏ Δ ⊢ □ A ▻ B ⟩ dhs-mlam = dh→dhs ∘ DH.mlam ∘ dhs→dh dhs-mlam⋆₀ : ∀ {Δ A Γ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → DHS⟨ Γ ⁏ ∅ ⊢ □⋆ Δ ▻⋯▻ A ⟩ dhs-mlam⋆₀ = dh→dhs ∘ DH.mlam⋆₀ ∘ dhs→dh dhs-det : ∀ {A B Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ A ▻ B ⟩ → DHS⟨ Γ , A ⁏ Δ ⊢ B ⟩ dhs-det = dh→dhs ∘ DH.det ∘ dhs→dh dhs-det⋆₀ : ∀ {A Γ Δ} → DHS⟨ ∅ ⁏ Δ ⊢ Γ ▻⋯▻ A ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ dhs-det⋆₀ = dh→dhs ∘ DH.det⋆₀ ∘ dhs→dh dhs-mdet : ∀ {A B Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ □ A ▻ B ⟩ → DHS⟨ Γ ⁏ Δ , A ⊢ B ⟩ dhs-mdet = dh→dhs ∘ DH.mdet ∘ dhs→dh dhs-mdet⋆₀ : ∀ {Δ A Γ} → DHS⟨ Γ ⁏ ∅ ⊢ □⋆ Δ ▻⋯▻ A ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ dhs-mdet⋆₀ = dh→dhs ∘ DH.mdet⋆₀ ∘ dhs→dh -- Context manipulation for dyadic Hilbert-style sequential. dhs-merge : ∀ {Δ A Γ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → DHS⟨ Γ ⧺ (□⋆ Δ) ⁏ ∅ ⊢ A ⟩ dhs-merge {Δ} = dh→dhs ∘ DH.merge ∘ dhs→dh dhs-split : ∀ {Δ A Γ} → DHS⟨ Γ ⧺ (□⋆ Δ) ⁏ ∅ ⊢ A ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ dhs-split {Δ} = dh→dhs ∘ DH.split ∘ dhs→dh -- Translation from closed Hilbert-style sequential to Hilbert-style sequential. chs→hs₀ : ∀ {A} → CHS.⊢ A → HS⟨ ∅ ⊢ A ⟩ chs→hs₀ (Ξ , ts) = Ξ , chs⊦→hs⊦ ts where chs⊦→hs⊦ : ∀ {Ξ} → CHS.⊦⊢ Ξ → HS⟨ ∅ ⊦⊢ Ξ ⟩ chs⊦→hs⊦ CHS.nil = HS.nil chs⊦→hs⊦ (CHS.mp i j ts) = HS.mp i j (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.ci ts) = HS.ci (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.ck ts) = HS.ck (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.cs ts) = HS.cs (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.cpair ts) = HS.cpair (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.cfst ts) = HS.cfst (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.csnd ts) = HS.csnd (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.unit ts) = HS.unit (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.nec ss ts) = HS.nec (chs⊦→hs⊦ ss) (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.cdist ts) = HS.cdist (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.cup ts) = HS.cup (chs⊦→hs⊦ ts) chs⊦→hs⊦ (CHS.cdown ts) = HS.cdown (chs⊦→hs⊦ ts) chs→hs : ∀ {A Γ} → CHS.⊢ Γ ▻⋯▻ A → HS⟨ Γ ⊢ A ⟩ chs→hs t = hs-det⋆₀ (chs→hs₀ t) -- Translation from Hilbert-style sequential to closed Hilbert-style sequential. hs₀→chs : ∀ {A} → HS⟨ ∅ ⊢ A ⟩ → CHS.⊢ A hs₀→chs (Ξ , ts) = Ξ , hs₀⊦→chs⊦ ts where hs₀⊦→chs⊦ : ∀ {Ξ} → HS⟨ ∅ ⊦⊢ Ξ ⟩ → CHS.⊦⊢ Ξ hs₀⊦→chs⊦ HS.nil = CHS.nil hs₀⊦→chs⊦ (HS.var () ts) hs₀⊦→chs⊦ (HS.mp i j ts) = CHS.mp i j (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.ci ts) = CHS.ci (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.ck ts) = CHS.ck (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.cs ts) = CHS.cs (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.cpair ts) = CHS.cpair (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.cfst ts) = CHS.cfst (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.csnd ts) = CHS.csnd (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.unit ts) = CHS.unit (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.nec ss ts) = CHS.nec (hs₀⊦→chs⊦ ss) (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.cdist ts) = CHS.cdist (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.cup ts) = CHS.cup (hs₀⊦→chs⊦ ts) hs₀⊦→chs⊦ (HS.cdown ts) = CHS.cdown (hs₀⊦→chs⊦ ts) hs→chs : ∀ {A Γ} → HS⟨ Γ ⊢ A ⟩ → CHS.⊢ Γ ▻⋯▻ A hs→chs t = hs₀→chs (hs-lam⋆₀ t) -- Translation from dyadic Hilbert-style sequential to Hilbert-style sequential. dhs₀→hs : ∀ {A Γ} → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ → HS⟨ Γ ⊢ A ⟩ dhs₀→hs (Ξ , ts) = Ξ , dhs₀⊦→hs⊦ ts where dhs₀⊦→hs⊦ : ∀ {Ξ Γ} → DHS⟨ Γ ⁏ ∅ ⊦⊢ Ξ ⟩ → HS⟨ Γ ⊦⊢ Ξ ⟩ dhs₀⊦→hs⊦ DHS.nil = HS.nil dhs₀⊦→hs⊦ (DHS.var i ts) = HS.var i (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.mp i j ts) = HS.mp i j (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.ci ts) = HS.ci (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.ck ts) = HS.ck (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.cs ts) = HS.cs (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.mvar () ts) dhs₀⊦→hs⊦ (DHS.nec ss ts) = HS.nec (dhs₀⊦→hs⊦ ss) (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.cdist ts) = HS.cdist (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.cup ts) = HS.cup (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.cdown ts) = HS.cdown (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.cpair ts) = HS.cpair (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.cfst ts) = HS.cfst (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.csnd ts) = HS.csnd (dhs₀⊦→hs⊦ ts) dhs₀⊦→hs⊦ (DHS.unit ts) = HS.unit (dhs₀⊦→hs⊦ ts) dhs→hs : ∀ {A Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → HS⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ dhs→hs = dhs₀→hs ∘ dhs-merge -- Translation from Hilbert-style sequential to dyadic Hilbert-style sequential. hs→dhs₀ : ∀ {A Γ} → HS⟨ Γ ⊢ A ⟩ → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ hs→dhs₀ (Ξ , ts) = Ξ , hs⊦→dhs₀⊦ ts where hs⊦→dhs₀⊦ : ∀ {Ξ Γ} → HS⟨ Γ ⊦⊢ Ξ ⟩ → DHS⟨ Γ ⁏ ∅ ⊦⊢ Ξ ⟩ hs⊦→dhs₀⊦ HS.nil = DHS.nil hs⊦→dhs₀⊦ (HS.var i ts) = DHS.var i (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.mp i j ts) = DHS.mp i j (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.ci ts) = DHS.ci (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.ck ts) = DHS.ck (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.cs ts) = DHS.cs (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.nec ss ts) = DHS.nec (hs⊦→dhs₀⊦ ss) (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.cdist ts) = DHS.cdist (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.cup ts) = DHS.cup (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.cdown ts) = DHS.cdown (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.cpair ts) = DHS.cpair (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.cfst ts) = DHS.cfst (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.csnd ts) = DHS.csnd (hs⊦→dhs₀⊦ ts) hs⊦→dhs₀⊦ (HS.unit ts) = DHS.unit (hs⊦→dhs₀⊦ ts) hs→dhs : ∀ {A Γ Δ} → HS⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ hs→dhs = dhs-split ∘ hs→dhs₀ -- Translation from closed Hilbert-style to Hilbert-style. ch→h₀ : ∀ {A} → CH.⊢ A → H⟨ ∅ ⊢ A ⟩ ch→h₀ (CH.app t u) = H.app (ch→h₀ t) (ch→h₀ u) ch→h₀ CH.ci = H.ci ch→h₀ CH.ck = H.ck ch→h₀ CH.cs = H.cs ch→h₀ CH.cpair = H.cpair ch→h₀ CH.cfst = H.cfst ch→h₀ CH.csnd = H.csnd ch→h₀ CH.unit = H.unit ch→h₀ (CH.box t) = H.box (ch→h₀ t) ch→h₀ CH.cdist = H.cdist ch→h₀ CH.cup = H.cup ch→h₀ CH.cdown = H.cdown ch→h : ∀ {A Γ} → CH.⊢ Γ ▻⋯▻ A → H⟨ Γ ⊢ A ⟩ ch→h t = H.det⋆₀ (ch→h₀ t) -- Translation from Hilbert-style to closed Hilbert-style. h₀→ch : ∀ {A} → H⟨ ∅ ⊢ A ⟩ → CH.⊢ A h₀→ch (H.var ()) h₀→ch (H.app t u) = CH.app (h₀→ch t) (h₀→ch u) h₀→ch H.ci = CH.ci h₀→ch H.ck = CH.ck h₀→ch H.cs = CH.cs h₀→ch H.cpair = CH.cpair h₀→ch H.cfst = CH.cfst h₀→ch H.csnd = CH.csnd h₀→ch H.unit = CH.unit h₀→ch (H.box t) = CH.box (h₀→ch t) h₀→ch H.cdist = CH.cdist h₀→ch H.cup = CH.cup h₀→ch H.cdown = CH.cdown h→ch : ∀ {A Γ} → H⟨ Γ ⊢ A ⟩ → CH.⊢ Γ ▻⋯▻ A h→ch t = h₀→ch (H.lam⋆₀ t) -- Translation from dyadic Hilbert-style to Hilbert-style. dh₀→h : ∀ {A Γ} → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ → H⟨ Γ ⊢ A ⟩ dh₀→h (DH.var i) = H.var i dh₀→h (DH.app t u) = H.app (dh₀→h t) (dh₀→h u) dh₀→h DH.ci = H.ci dh₀→h DH.ck = H.ck dh₀→h DH.cs = H.cs dh₀→h (DH.mvar ()) dh₀→h (DH.box t) = H.box (dh₀→h t) dh₀→h DH.cdist = H.cdist dh₀→h DH.cup = H.cup dh₀→h DH.cdown = H.cdown dh₀→h DH.cpair = H.cpair dh₀→h DH.cfst = H.cfst dh₀→h DH.csnd = H.csnd dh₀→h DH.unit = H.unit dh→h : ∀ {A Γ Δ} → DH⟨ Γ ⁏ Δ ⊢ A ⟩ → H⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ dh→h = dh₀→h ∘ DH.merge -- Translation from Hilbert-style to dyadic Hilbert-style. h→dh₀ : ∀ {A Γ} → H⟨ Γ ⊢ A ⟩ → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ h→dh₀ (H.var i) = DH.var i h→dh₀ (H.app t u) = DH.app (h→dh₀ t) (h→dh₀ u) h→dh₀ H.ci = DH.ci h→dh₀ H.ck = DH.ck h→dh₀ H.cs = DH.cs h→dh₀ (H.box t) = DH.box (h→dh₀ t) h→dh₀ H.cdist = DH.cdist h→dh₀ H.cup = DH.cup h→dh₀ H.cdown = DH.cdown h→dh₀ H.cpair = DH.cpair h→dh₀ H.cfst = DH.cfst h→dh₀ H.csnd = DH.csnd h→dh₀ H.unit = DH.unit h→dh : ∀ {A Γ Δ} → H⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ → DH⟨ Γ ⁏ Δ ⊢ A ⟩ h→dh = DH.split ∘ h→dh₀ -- Translation from Hilbert-style to Gentzen-style. h→g : ∀ {A Γ} → H⟨ Γ ⊢ A ⟩ → G⟨ Γ ⊢ A ⟩ h→g (H.var i) = G.var i h→g (H.app t u) = G.app (h→g t) (h→g u) h→g H.ci = G.ci h→g H.ck = G.ck h→g H.cs = G.cs h→g (H.box t) = G.box (h→g t) h→g H.cdist = G.cdist h→g H.cup = G.cup h→g H.cdown = G.cdown h→g H.cpair = G.cpair h→g H.cfst = G.cfst h→g H.csnd = G.csnd h→g H.unit = G.unit -- Translation from Gentzen-style to Hilbert-style. mutual g→h : ∀ {A Γ} → G⟨ Γ ⊢ A ⟩ → H⟨ Γ ⊢ A ⟩ g→h (G.var i) = H.var i g→h (G.lam t) = H.lam (g→h t) g→h (G.app t u) = H.app (g→h t) (g→h u) g→h (G.multibox ts u) = H.multibox (g→h⋆ ts) (g→h u) g→h (G.down t) = H.down (g→h t) g→h (G.pair t u) = H.pair (g→h t) (g→h u) g→h (G.fst t) = H.fst (g→h t) g→h (G.snd t) = H.snd (g→h t) g→h G.unit = H.unit g→h⋆ : ∀ {Ξ Γ} → G⟨ Γ ⊢⋆ Ξ ⟩ → H⟨ Γ ⊢⋆ Ξ ⟩ g→h⋆ {∅} ∙ = ∙ g→h⋆ {Ξ , A} (ts , t) = g→h⋆ ts , g→h t -- Translation from dyadic Hilbert-style to dyadic Gentzen-style. dh→dg : ∀ {A Γ Δ} → DH⟨ Γ ⁏ Δ ⊢ A ⟩ → DG⟨ Γ ⁏ Δ ⊢ A ⟩ dh→dg (DH.var i) = DG.var i dh→dg (DH.app t u) = DG.app (dh→dg t) (dh→dg u) dh→dg DH.ci = DG.ci dh→dg DH.ck = DG.ck dh→dg DH.cs = DG.cs dh→dg (DH.mvar i) = DG.mvar i dh→dg (DH.box t) = DG.box (dh→dg t) dh→dg DH.cdist = DG.cdist dh→dg DH.cup = DG.cup dh→dg DH.cdown = DG.cdown dh→dg DH.cpair = DG.cpair dh→dg DH.cfst = DG.cfst dh→dg DH.csnd = DG.csnd dh→dg DH.unit = DG.unit -- Translation from dyadic Gentzen-style to dyadic Hilbert-style. dg→dh : ∀ {A Γ Δ} → DG⟨ Γ ⁏ Δ ⊢ A ⟩ → DH⟨ Γ ⁏ Δ ⊢ A ⟩ dg→dh (DG.var i) = DH.var i dg→dh (DG.lam t) = DH.lam (dg→dh t) dg→dh (DG.app t u) = DH.app (dg→dh t) (dg→dh u) dg→dh (DG.mvar i) = DH.mvar i dg→dh (DG.box t) = DH.box (dg→dh t) dg→dh (DG.unbox t u) = DH.unbox (dg→dh t) (dg→dh u) dg→dh (DG.pair t u) = DH.pair (dg→dh t) (dg→dh u) dg→dh (DG.fst t) = DH.fst (dg→dh t) dg→dh (DG.snd t) = DH.snd (dg→dh t) dg→dh DG.unit = DH.unit -- Translation from Gentzen-style to dyadic Gentzen-style. mutual g→dg₀ : ∀ {A Γ} → G⟨ Γ ⊢ A ⟩ → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ g→dg₀ (G.var i) = DG.var i g→dg₀ (G.lam t) = DG.lam (g→dg₀ t) g→dg₀ (G.app t u) = DG.app (g→dg₀ t) (g→dg₀ u) g→dg₀ (G.multibox ts u) = DG.multibox (g→dg₀⋆ ts) (g→dg₀ u) g→dg₀ (G.down t) = DG.down (g→dg₀ t) g→dg₀ (G.pair t u) = DG.pair (g→dg₀ t) (g→dg₀ u) g→dg₀ (G.fst t) = DG.fst (g→dg₀ t) g→dg₀ (G.snd t) = DG.snd (g→dg₀ t) g→dg₀ G.unit = DG.unit g→dg₀⋆ : ∀ {Ξ Γ} → G⟨ Γ ⊢⋆ Ξ ⟩ → DG⟨ Γ ⁏ ∅ ⊢⋆ Ξ ⟩ g→dg₀⋆ {∅} ∙ = ∙ g→dg₀⋆ {Ξ , A} (ts , t) = g→dg₀⋆ ts , g→dg₀ t g→dg : ∀ {A Γ Δ} → G⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ → DG⟨ Γ ⁏ Δ ⊢ A ⟩ g→dg = DG.split ∘ g→dg₀ -- Translation from Hilbert-style to labelled Gentzen-style. h→lg : ∀ {x A Γ Λ} → H⟨ Γ ⊢ A ⟩ → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ h→lg (H.var i) = LG.var i h→lg (H.app t u) = LG.app (h→lg t) (h→lg u) h→lg H.ci = LG.ci h→lg H.ck = LG.ck h→lg H.cs = LG.cs h→lg (H.box t) = LG.box (h→lg t) h→lg H.cdist = LG.cdist h→lg H.cup = LG.cup h→lg H.cdown = LG.cdown h→lg H.cpair = LG.cpair h→lg H.cfst = LG.cfst h→lg H.csnd = LG.csnd h→lg H.unit = LG.unit -- Translation from labelled Gentzen-style to Hilbert-style. -- FIXME: Stronger hypothesis? postulate h-oops : ∀ {x A Γ Λ} → (∀ {y} → LG⟨ Γ ⁏ Λ , x ↝ y ⊢ A ◎ y ⟩) → H⟨ Γ ⊢ □ A ⟩ lg→h : ∀ {x A Γ Λ} → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ → H⟨ Γ ⊢ A ⟩ lg→h (LG.var i) = H.var i lg→h (LG.lam t) = H.lam (lg→h t) lg→h (LG.app t u) = H.app (lg→h t) (lg→h u) lg→h (LG.scan t) = h-oops t lg→h (LG.move t u) = H.down (lg→h t) lg→h (LG.pair t u) = H.pair (lg→h t) (lg→h u) lg→h (LG.fst t) = H.fst (lg→h t) lg→h (LG.snd t) = H.snd (lg→h t) lg→h LG.unit = H.unit -- Translation from Gentzen-style to labelled Gentzen-style. mutual g→lg : ∀ {x A Γ Λ} → G⟨ Γ ⊢ A ⟩ → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ g→lg (G.var i) = LG.var i g→lg (G.lam t) = LG.lam (g→lg t) g→lg (G.app t u) = LG.app (g→lg t) (g→lg u) g→lg (G.multibox ts u) = LG.multibox (g→lg⋆ ts) (g→lg u) g→lg (G.down t) = LG.move (g→lg t) LG.rrefl g→lg (G.pair t u) = LG.pair (g→lg t) (g→lg u) g→lg (G.fst t) = LG.fst (g→lg t) g→lg (G.snd t) = LG.snd (g→lg t) g→lg G.unit = LG.unit g→lg⋆ : ∀ {x Ξ Γ Λ} → G⟨ Γ ⊢⋆ Ξ ⟩ → LG⟨ Γ ⁏ Λ ⊢⋆ Ξ ◎⋆ x ⟩ g→lg⋆ {x} {∅} ∙ = ∙ g→lg⋆ {x} {Ξ , A} (ts , t) = g→lg⋆ ts , g→lg t -- Translation from labelled Gentzen-style to Gentzen-style. -- FIXME: Stronger hypothesis? postulate g-oops : ∀ {x A Γ Λ} → (∀ {y} → LG⟨ Γ ⁏ Λ , x ↝ y ⊢ A ◎ y ⟩) → G⟨ Γ ⊢ □ A ⟩ lg→g : ∀ {x A Γ Λ} → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ → G⟨ Γ ⊢ A ⟩ lg→g (LG.var i) = G.var i lg→g (LG.lam t) = G.lam (lg→g t) lg→g (LG.app t u) = G.app (lg→g t) (lg→g u) lg→g (LG.scan t) = g-oops t lg→g (LG.move t u) = G.down (lg→g t) lg→g (LG.pair t u) = G.pair (lg→g t) (lg→g u) lg→g (LG.fst t) = G.fst (lg→g t) lg→g (LG.snd t) = G.snd (lg→g t) lg→g LG.unit = G.unit -- Additional translations from closed Hilbert-style sequential. chs→h₀ : ∀ {A} → CHS.⊢ A → H⟨ ∅ ⊢ A ⟩ chs→h₀ = ch→h₀ ∘ chs→ch chs→h : ∀ {A Γ} → CHS.⊢ Γ ▻⋯▻ A → H⟨ Γ ⊢ A ⟩ chs→h = ch→h ∘ chs→ch chs→g₀ : ∀ {A} → CHS.⊢ A → G⟨ ∅ ⊢ A ⟩ chs→g₀ = h→g ∘ chs→h₀ chs→g : ∀ {A Γ} → CHS.⊢ Γ ▻⋯▻ A → G⟨ Γ ⊢ A ⟩ chs→g = h→g ∘ chs→h chs→dhs₀₀ : ∀ {A} → CHS.⊢ A → DHS⟨ ∅ ⁏ ∅ ⊢ A ⟩ chs→dhs₀₀ = hs→dhs₀ ∘ chs→hs₀ chs→dhs₀ : ∀ {A Γ} → CHS.⊢ Γ ▻⋯▻ A → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ chs→dhs₀ = hs→dhs₀ ∘ chs→hs chs→dhs : ∀ {A Γ Δ} → CHS.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ chs→dhs = hs→dhs ∘ chs→hs chs→dh₀₀ : ∀ {A} → CHS.⊢ A → DH⟨ ∅ ⁏ ∅ ⊢ A ⟩ chs→dh₀₀ = h→dh₀ ∘ chs→h₀ chs→dh₀ : ∀ {A Γ} → CHS.⊢ Γ ▻⋯▻ A → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ chs→dh₀ = h→dh₀ ∘ chs→h chs→dh : ∀ {A Γ Δ} → CHS.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A → DH⟨ Γ ⁏ Δ ⊢ A ⟩ chs→dh = h→dh ∘ chs→h chs→dg₀₀ : ∀ {A} → CHS.⊢ A → DG⟨ ∅ ⁏ ∅ ⊢ A ⟩ chs→dg₀₀ = g→dg₀ ∘ chs→g₀ chs→dg₀ : ∀ {A Γ} → CHS.⊢ Γ ▻⋯▻ A → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ chs→dg₀ = g→dg₀ ∘ chs→g chs→dg : ∀ {A Γ Δ} → CHS.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A → DG⟨ Γ ⁏ Δ ⊢ A ⟩ chs→dg = g→dg ∘ chs→g chs→lg₀ : ∀ {x A Λ} → CHS.⊢ A → LG⟨ ∅ ⁏ Λ ⊢ A ◎ x ⟩ chs→lg₀ = g→lg ∘ chs→g₀ chs→lg : ∀ {x A Γ Λ} → CHS.⊢ Γ ▻⋯▻ A → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ chs→lg = g→lg ∘ chs→g -- Additional translations from closed Hilbert-style. ch→hs₀ : ∀ {A} → CH.⊢ A → HS⟨ ∅ ⊢ A ⟩ ch→hs₀ = chs→hs ∘ ch→chs ch→hs : ∀ {A Γ} → CH.⊢ Γ ▻⋯▻ A → HS⟨ Γ ⊢ A ⟩ ch→hs = chs→hs ∘ ch→chs ch→g₀ : ∀ {A} → CH.⊢ A → G⟨ ∅ ⊢ A ⟩ ch→g₀ = h→g ∘ ch→h₀ ch→g : ∀ {A Γ} → CH.⊢ Γ ▻⋯▻ A → G⟨ Γ ⊢ A ⟩ ch→g = h→g ∘ ch→h ch→dhs₀₀ : ∀ {A} → CH.⊢ A → DHS⟨ ∅ ⁏ ∅ ⊢ A ⟩ ch→dhs₀₀ = hs→dhs₀ ∘ ch→hs₀ ch→dhs₀ : ∀ {A Γ} → CH.⊢ Γ ▻⋯▻ A → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ ch→dhs₀ = hs→dhs₀ ∘ ch→hs ch→dhs : ∀ {A Γ Δ} → CH.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ ch→dhs = hs→dhs ∘ ch→hs ch→dh₀₀ : ∀ {A} → CH.⊢ A → DH⟨ ∅ ⁏ ∅ ⊢ A ⟩ ch→dh₀₀ = h→dh₀ ∘ ch→h₀ ch→dh₀ : ∀ {A Γ} → CH.⊢ Γ ▻⋯▻ A → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ ch→dh₀ = h→dh₀ ∘ ch→h ch→dh : ∀ {A Γ Δ} → CH.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A → DH⟨ Γ ⁏ Δ ⊢ A ⟩ ch→dh = h→dh ∘ ch→h ch→dg₀₀ : ∀ {A} → CH.⊢ A → DG⟨ ∅ ⁏ ∅ ⊢ A ⟩ ch→dg₀₀ = g→dg₀ ∘ ch→g₀ ch→dg₀ : ∀ {A Γ} → CH.⊢ Γ ▻⋯▻ A → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ ch→dg₀ = g→dg₀ ∘ ch→g ch→dg : ∀ {A Γ Δ} → CH.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A → DG⟨ Γ ⁏ Δ ⊢ A ⟩ ch→dg = g→dg ∘ ch→g ch→lg₀ : ∀ {x A Λ} → CH.⊢ A → LG⟨ ∅ ⁏ Λ ⊢ A ◎ x ⟩ ch→lg₀ = g→lg ∘ ch→g₀ ch→lg : ∀ {x A Γ Λ} → CH.⊢ Γ ▻⋯▻ A → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ ch→lg = g→lg ∘ ch→g -- Additional translations from Hilbert-style sequential. hs₀→ch : ∀ {A} → HS⟨ ∅ ⊢ A ⟩ → CH.⊢ A hs₀→ch = chs→ch ∘ hs₀→chs hs→ch : ∀ {A Γ} → HS⟨ Γ ⊢ A ⟩ → CH.⊢ Γ ▻⋯▻ A hs→ch = chs→ch ∘ hs→chs hs→g : ∀ {A Γ} → HS⟨ Γ ⊢ A ⟩ → G⟨ Γ ⊢ A ⟩ hs→g = h→g ∘ hs→h hs→dh₀ : ∀ {A Γ} → HS⟨ Γ ⊢ A ⟩ → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ hs→dh₀ = h→dh₀ ∘ hs→h hs→dh : ∀ {A Γ Δ} → HS⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ → DH⟨ Γ ⁏ Δ ⊢ A ⟩ hs→dh = h→dh ∘ hs→h hs→dg₀ : ∀ {A Γ} → HS⟨ Γ ⊢ A ⟩ → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ hs→dg₀ = dh→dg ∘ hs→dh₀ hs→dg : ∀ {A Γ Δ} → HS⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ → DG⟨ Γ ⁏ Δ ⊢ A ⟩ hs→dg = dh→dg ∘ hs→dh hs→lg : ∀ {x A Γ Λ} → HS⟨ Γ ⊢ A ⟩ → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ hs→lg = h→lg ∘ hs→h -- Additional translations from Hilbert-style. h₀→chs : ∀ {A} → H⟨ ∅ ⊢ A ⟩ → CHS.⊢ A h₀→chs = ch→chs ∘ h₀→ch h→chs : ∀ {A Γ} → H⟨ Γ ⊢ A ⟩ → CHS.⊢ Γ ▻⋯▻ A h→chs = ch→chs ∘ h→ch h→dhs₀ : ∀ {A Γ} → H⟨ Γ ⊢ A ⟩ → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ h→dhs₀ = hs→dhs₀ ∘ h→hs h→dhs : ∀ {A Γ Δ} → H⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ h→dhs = hs→dhs ∘ h→hs h→dg₀ : ∀ {A Γ} → H⟨ Γ ⊢ A ⟩ → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ h→dg₀ = dh→dg ∘ h→dh₀ h→dg : ∀ {A Γ Δ} → H⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ → DG⟨ Γ ⁏ Δ ⊢ A ⟩ h→dg = dh→dg ∘ h→dh -- Additional translations from Gentzen-style. g₀→chs : ∀ {A} → G⟨ ∅ ⊢ A ⟩ → CHS.⊢ A g₀→chs = h₀→chs ∘ g→h g→chs : ∀ {A Γ} → G⟨ Γ ⊢ A ⟩ → CHS.⊢ Γ ▻⋯▻ A g→chs = h→chs ∘ g→h g₀→ch : ∀ {A} → G⟨ ∅ ⊢ A ⟩ → CH.⊢ A g₀→ch = h₀→ch ∘ g→h g→ch : ∀ {A Γ} → G⟨ Γ ⊢ A ⟩ → CH.⊢ Γ ▻⋯▻ A g→ch = h→ch ∘ g→h g→hs : ∀ {A Γ} → G⟨ Γ ⊢ A ⟩ → HS⟨ Γ ⊢ A ⟩ g→hs = h→hs ∘ g→h g→dhs₀ : ∀ {A Γ} → G⟨ Γ ⊢ A ⟩ → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ g→dhs₀ = h→dhs₀ ∘ g→h g→dhs : ∀ {A Γ Δ} → G⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ g→dhs = h→dhs ∘ g→h g→dh₀ : ∀ {A Γ} → G⟨ Γ ⊢ A ⟩ → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ g→dh₀ = h→dh₀ ∘ g→h g→dh : ∀ {A Γ Δ} → G⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ → DH⟨ Γ ⁏ Δ ⊢ A ⟩ g→dh = h→dh ∘ g→h -- Additional translations from dyadic Hilbert-style sequential. dhs₀₀→chs : ∀ {A} → DHS⟨ ∅ ⁏ ∅ ⊢ A ⟩ → CHS.⊢ A dhs₀₀→chs = hs₀→chs ∘ dhs₀→hs dhs₀→chs : ∀ {A Γ} → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ → CHS.⊢ Γ ▻⋯▻ A dhs₀→chs = hs→chs ∘ dhs₀→hs dhs→chs : ∀ {A Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → CHS.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A dhs→chs = hs→chs ∘ dhs→hs dhs₀₀→ch : ∀ {A} → DHS⟨ ∅ ⁏ ∅ ⊢ A ⟩ → CH.⊢ A dhs₀₀→ch = hs₀→ch ∘ dhs₀→hs dhs₀→ch : ∀ {A Γ} → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ → CH.⊢ Γ ▻⋯▻ A dhs₀→ch = hs→ch ∘ dhs₀→hs dhs→ch : ∀ {A Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → CH.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A dhs→ch = hs→ch ∘ dhs→hs dhs₀→h : ∀ {A Γ} → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ → H⟨ Γ ⊢ A ⟩ dhs₀→h = hs→h ∘ dhs₀→hs dhs→h : ∀ {A Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → H⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ dhs→h = hs→h ∘ dhs→hs dhs₀→g : ∀ {A Γ} → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ → G⟨ Γ ⊢ A ⟩ dhs₀→g = hs→g ∘ dhs₀→hs dhs→g : ∀ {A Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → G⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ dhs→g = hs→g ∘ dhs→hs dhs→dg : ∀ {A Γ Δ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → DG⟨ Γ ⁏ Δ ⊢ A ⟩ dhs→dg = dh→dg ∘ dhs→dh dhs₀→lg : ∀ {x A Γ Λ} → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ dhs₀→lg = hs→lg ∘ dhs₀→hs dhs→lg : ∀ {x A Γ Δ Λ} → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ → LG⟨ Γ ⧺ (□⋆ Δ) ⁏ Λ ⊢ A ◎ x ⟩ dhs→lg = hs→lg ∘ dhs→hs -- Additional translations from dyadic Hilbert-style. dh₀₀→chs : ∀ {A} → DH⟨ ∅ ⁏ ∅ ⊢ A ⟩ → CHS.⊢ A dh₀₀→chs = h₀→chs ∘ dh₀→h dh₀→chs : ∀ {A Γ} → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ → CHS.⊢ Γ ▻⋯▻ A dh₀→chs = h→chs ∘ dh₀→h dh→chs : ∀ {A Γ Δ} → DH⟨ Γ ⁏ Δ ⊢ A ⟩ → CHS.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A dh→chs = h→chs ∘ dh→h dh₀₀→ch : ∀ {A} → DH⟨ ∅ ⁏ ∅ ⊢ A ⟩ → CH.⊢ A dh₀₀→ch = h₀→ch ∘ dh₀→h dh₀→ch : ∀ {A Γ} → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ → CH.⊢ Γ ▻⋯▻ A dh₀→ch = h→ch ∘ dh₀→h dh→ch : ∀ {A Γ Δ} → DH⟨ Γ ⁏ Δ ⊢ A ⟩ → CH.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A dh→ch = h→ch ∘ dh→h dh₀→hs : ∀ {A Γ} → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ → HS⟨ Γ ⊢ A ⟩ dh₀→hs = h→hs ∘ dh₀→h dh→hs : ∀ {A Γ Δ} → DH⟨ Γ ⁏ Δ ⊢ A ⟩ → HS⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ dh→hs = h→hs ∘ dh→h dh₀→g : ∀ {A Γ} → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ → G⟨ Γ ⊢ A ⟩ dh₀→g = h→g ∘ dh₀→h dh→g : ∀ {A Γ Δ} → DH⟨ Γ ⁏ Δ ⊢ A ⟩ → G⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ dh→g = h→g ∘ dh→h dh₀→lg : ∀ {x A Γ Λ} → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ dh₀→lg = h→lg ∘ dh₀→h dh→lg : ∀ {x A Γ Δ Λ} → DH⟨ Γ ⁏ Δ ⊢ A ⟩ → LG⟨ Γ ⧺ (□⋆ Δ) ⁏ Λ ⊢ A ◎ x ⟩ dh→lg = h→lg ∘ dh→h -- Additional translations from dyadic Gentzen-style. dg₀₀→chs : ∀ {A} → DG⟨ ∅ ⁏ ∅ ⊢ A ⟩ → CHS.⊢ A dg₀₀→chs = dh₀→chs ∘ dg→dh dg₀→chs : ∀ {A Γ} → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ → CHS.⊢ Γ ▻⋯▻ A dg₀→chs = dh→chs ∘ dg→dh dg→chs : ∀ {A Γ Δ} → DG⟨ Γ ⁏ Δ ⊢ A ⟩ → CHS.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A dg→chs = dh→chs ∘ dg→dh dg₀₀→ch : ∀ {A} → DG⟨ ∅ ⁏ ∅ ⊢ A ⟩ → CH.⊢ A dg₀₀→ch = dh₀→ch ∘ dg→dh dg₀→ch : ∀ {A Γ} → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ → CH.⊢ Γ ▻⋯▻ A dg₀→ch = dh→ch ∘ dg→dh dg→ch : ∀ {A Γ Δ} → DG⟨ Γ ⁏ Δ ⊢ A ⟩ → CH.⊢ Γ ⧺ (□⋆ Δ) ▻⋯▻ A dg→ch = dh→ch ∘ dg→dh dg₀→hs : ∀ {A Γ} → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ → HS⟨ Γ ⊢ A ⟩ dg₀→hs = dh₀→hs ∘ dg→dh dg→hs : ∀ {A Γ Δ} → DG⟨ Γ ⁏ Δ ⊢ A ⟩ → HS⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ dg→hs = dh→hs ∘ dg→dh dg₀→h : ∀ {A Γ} → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ → H⟨ Γ ⊢ A ⟩ dg₀→h = dh₀→h ∘ dg→dh dg→h : ∀ {A Γ Δ} → DG⟨ Γ ⁏ Δ ⊢ A ⟩ → H⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ dg→h = dh→h ∘ dg→dh -- NOTE: Direct translation fails the termination check. dg₀→g : ∀ {A Γ} → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ → G⟨ Γ ⊢ A ⟩ dg₀→g = h→g ∘ dg₀→h dg→g : ∀ {A Γ Δ} → DG⟨ Γ ⁏ Δ ⊢ A ⟩ → G⟨ Γ ⧺ (□⋆ Δ) ⊢ A ⟩ dg→g = h→g ∘ dg→h dg→dhs : ∀ {A Γ Δ} → DG⟨ Γ ⁏ Δ ⊢ A ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ dg→dhs = dh→dhs ∘ dg→dh dg₀→lg : ∀ {x A Γ Λ} → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ dg₀→lg = g→lg ∘ dg₀→g dg→lg : ∀ {x A Γ Δ Λ} → DG⟨ Γ ⁏ Δ ⊢ A ⟩ → LG⟨ Γ ⧺ (□⋆ Δ) ⁏ Λ ⊢ A ◎ x ⟩ dg→lg = g→lg ∘ dg→g -- Additional translations from labelled Gentzen-style. lg₀→chs : ∀ {x A Λ} → LG⟨ ∅ ⁏ Λ ⊢ A ◎ x ⟩ → CHS.⊢ A lg₀→chs = h₀→chs ∘ lg→h lg→chs : ∀ {x A Γ Λ} → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ → CHS.⊢ Γ ▻⋯▻ A lg→chs = h→chs ∘ lg→h lg₀→ch : ∀ {x A Λ} → LG⟨ ∅ ⁏ Λ ⊢ A ◎ x ⟩ → CH.⊢ A lg₀→ch = h₀→ch ∘ lg→h lg→ch : ∀ {x A Γ Λ} → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ → CH.⊢ Γ ▻⋯▻ A lg→ch = h→ch ∘ lg→h lg→hs : ∀ {x A Γ Λ} → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ → HS⟨ Γ ⊢ A ⟩ lg→hs = h→hs ∘ lg→h lg→dhs₀ : ∀ {x A Γ Λ} → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ → DHS⟨ Γ ⁏ ∅ ⊢ A ⟩ lg→dhs₀ = h→dhs₀ ∘ lg→h lg→dhs : ∀ {x A Γ Δ Λ} → LG⟨ Γ ⧺ (□⋆ Δ) ⁏ Λ ⊢ A ◎ x ⟩ → DHS⟨ Γ ⁏ Δ ⊢ A ⟩ lg→dhs = h→dhs ∘ lg→h lg→dh₀ : ∀ {x A Γ Λ} → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ → DH⟨ Γ ⁏ ∅ ⊢ A ⟩ lg→dh₀ = h→dh₀ ∘ lg→h lg→dh : ∀ {x A Γ Δ Λ} → LG⟨ Γ ⧺ (□⋆ Δ) ⁏ Λ ⊢ A ◎ x ⟩ → DH⟨ Γ ⁏ Δ ⊢ A ⟩ lg→dh = h→dh ∘ lg→h lg→dg₀ : ∀ {x A Γ Λ} → LG⟨ Γ ⁏ Λ ⊢ A ◎ x ⟩ → DG⟨ Γ ⁏ ∅ ⊢ A ⟩ lg→dg₀ = h→dg₀ ∘ lg→h lg→dg : ∀ {x A Γ Δ Λ} → LG⟨ Γ ⧺ (□⋆ Δ) ⁏ Λ ⊢ A ◎ x ⟩ → DG⟨ Γ ⁏ Δ ⊢ A ⟩ lg→dg = h→dg ∘ lg→h ",16245,True,3968.8452294758727,median "{-# OPTIONS --without-K --exact-split --safe #-} module 08-equivalences where import 07-finite-sets open 07-finite-sets public -------------------------------------------------------------------------------- -- Section 8.1 Homotopies -- Definition 8.1.2 _~_ : {i j : Level} {A : UU i} {B : A → UU j} (f g : (x : A) → B x) → UU (i ⊔ j) f ~ g = (x : _) → Id (f x) (g x) -- Example 8.1.3 neg-neg-𝟚 : (neg-𝟚 ∘ neg-𝟚) ~ id neg-neg-𝟚 true = refl neg-neg-𝟚 false = refl -- Definition 8.1.5 refl-htpy : {i j : Level} {A : UU i} {B : A → UU j} {f : (x : A) → B x} → f ~ f refl-htpy x = refl {- Most of the time we get by with refl-htpy. However, sometimes Agda wants us to specify the implicit argument. The it is easier to call refl-htpy' than to use Agda's {f = ?} notation. -} refl-htpy' : {i j : Level} {A : UU i} {B : A → UU j} (f : (x : A) → B x) → f ~ f refl-htpy' f = refl-htpy htpy-inv : {i j : Level} {A : UU i} {B : A → UU j} {f g : (x : A) → B x} → (f ~ g) → (g ~ f) htpy-inv H x = inv (H x) _∙h_ : {i j : Level} {A : UU i} {B : A → UU j} {f g h : (x : A) → B x} → (f ~ g) → (g ~ h) → (f ~ h) _∙h_ H K x = (H x) ∙ (K x) htpy-concat : {i j : Level} {A : UU i} {B : A → UU j} {f g : (x : A) → B x} → (f ~ g) → (h : (x : A) → B x) → (g ~ h) → (f ~ h) htpy-concat H h K x = concat (H x) (h x) (K x) htpy-concat' : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} (f : (x : A) → B x) {g h : (x : A) → B x} → (g ~ h) → (f ~ g) → (f ~ h) htpy-concat' f K H = H ∙h K -- Proposition 8.1.6 -- Proposition 8.1.6 (i) htpy-assoc : {i j : Level} {A : UU i} {B : A → UU j} {f g h k : (x : A) → B x} → (H : f ~ g) → (K : g ~ h) → (L : h ~ k) → ((H ∙h K) ∙h L) ~ (H ∙h (K ∙h L)) htpy-assoc H K L x = assoc (H x) (K x) (L x) -- Proposition 8.1.6 (ii) htpy-left-unit : {i j : Level} {A : UU i} {B : A → UU j} {f g : (x : A) → B x} {H : f ~ g} → (refl-htpy ∙h H) ~ H htpy-left-unit x = left-unit htpy-right-unit : {i j : Level} {A : UU i} {B : A → UU j} {f g : (x : A) → B x} {H : f ~ g} → (H ∙h refl-htpy) ~ H htpy-right-unit x = right-unit -- Proposition 8.1.6 (iii) htpy-left-inv : {i j : Level} {A : UU i} {B : A → UU j} {f g : (x : A) → B x} (H : f ~ g) → ((htpy-inv H) ∙h H) ~ refl-htpy htpy-left-inv H x = left-inv (H x) htpy-right-inv : {i j : Level} {A : UU i} {B : A → UU j} {f g : (x : A) → B x} (H : f ~ g) → (H ∙h (htpy-inv H)) ~ refl-htpy htpy-right-inv H x = right-inv (H x) -- Definition 8.1.7 -- Definition 8.1.7 (i) htpy-left-whisk : {i j k : Level} {A : UU i} {B : UU j} {C : UU k} (h : B → C) {f g : A → B} → (f ~ g) → ((h ∘ f) ~ (h ∘ g)) htpy-left-whisk h H x = ap h (H x) _·l_ = htpy-left-whisk -- Definition 8.1.7 (ii) htpy-right-whisk : {i j k : Level} {A : UU i} {B : UU j} {C : UU k} {g h : B → C} (H : g ~ h) (f : A → B) → ((g ∘ f) ~ (h ∘ f)) htpy-right-whisk H f x = H (f x) _·r_ = htpy-right-whisk -------------------------------------------------------------------------------- -- Section 8.2 Bi-invertible maps -- Definition 8.2.1 -- Definition 8.2.1 (i) sec : {i j : Level} {A : UU i} {B : UU j} (f : A → B) → UU (i ⊔ j) sec {i} {j} {A} {B} f = Σ (B → A) (λ g → (f ∘ g) ~ id) -- Definition 8.2.1 (ii) retr : {i j : Level} {A : UU i} {B : UU j} (f : A → B) → UU (i ⊔ j) retr {i} {j} {A} {B} f = Σ (B → A) (λ g → (g ∘ f) ~ id) _retract-of_ : {i j : Level} → UU i → UU j → UU (i ⊔ j) A retract-of B = Σ (A → B) retr section-retract-of : {i j : Level} {A : UU i} {B : UU j} → A retract-of B → A → B section-retract-of = pr1 retr-section-retract-of : {i j : Level} {A : UU i} {B : UU j} (R : A retract-of B) → retr (section-retract-of R) retr-section-retract-of = pr2 retraction-retract-of : {i j : Level} {A : UU i} {B : UU j} → (A retract-of B) → B → A retraction-retract-of R = pr1 (retr-section-retract-of R) is-retr-retraction-retract-of : {i j : Level} {A : UU i} {B : UU j} (R : A retract-of B) → ((retraction-retract-of R) ∘ (section-retract-of R)) ~ id is-retr-retraction-retract-of R = pr2 (retr-section-retract-of R) -- Definition 8.2.1 (ii) is-equiv : {i j : Level} {A : UU i} {B : UU j} (f : A → B) → UU (i ⊔ j) is-equiv f = sec f × retr f _≃_ : {i j : Level} (A : UU i) (B : UU j) → UU (i ⊔ j) A ≃ B = Σ (A → B) (λ f → is-equiv f) map-equiv : {i j : Level} {A : UU i} {B : UU j} → (A ≃ B) → (A → B) map-equiv e = pr1 e is-equiv-map-equiv : {i j : Level} {A : UU i} {B : UU j} (e : A ≃ B) → is-equiv (map-equiv e) is-equiv-map-equiv e = pr2 e -- Example 8.2.3 is-equiv-id : {i : Level} (A : UU i) → is-equiv (id {i} {A}) is-equiv-id A = pair (pair id refl-htpy) (pair id refl-htpy) equiv-id : {i : Level} (A : UU i) → A ≃ A equiv-id A = pair id (is-equiv-id A) -- Example 8.2.4 abstract is-equiv-neg-𝟚 : is-equiv neg-𝟚 is-equiv-neg-𝟚 = pair (pair neg-𝟚 neg-neg-𝟚) (pair neg-𝟚 neg-neg-𝟚) equiv-neg-𝟚 : bool ≃ bool equiv-neg-𝟚 = pair neg-𝟚 is-equiv-neg-𝟚 -- Example 8.2.5 -- We show that succ-ℤ is an equivalence abstract is-equiv-succ-ℤ : is-equiv succ-ℤ is-equiv-succ-ℤ = pair (pair pred-ℤ right-inverse-pred-ℤ) (pair pred-ℤ left-inverse-pred-ℤ) equiv-succ-ℤ : ℤ ≃ ℤ equiv-succ-ℤ = pair succ-ℤ is-equiv-succ-ℤ -- We show that pred-ℤ is an equivalence abstract is-equiv-pred-ℤ : is-equiv pred-ℤ is-equiv-pred-ℤ = pair (pair succ-ℤ left-inverse-pred-ℤ) (pair succ-ℤ right-inverse-pred-ℤ) equiv-pred-ℤ : ℤ ≃ ℤ equiv-pred-ℤ = pair pred-ℤ is-equiv-pred-ℤ -- We show that add-ℤ x is an equivalence abstract is-equiv-add-ℤ : (x : ℤ) → is-equiv (add-ℤ x) is-equiv-add-ℤ x = pair ( pair ( add-ℤ (neg-ℤ x)) ( λ y → ( inv (associative-add-ℤ x (neg-ℤ x) y)) ∙ ( ( ap (add-ℤ' y) (right-inverse-law-add-ℤ x)) ∙ ( left-unit-law-add-ℤ y)))) ( pair ( add-ℤ (neg-ℤ x)) ( λ y → ( inv (associative-add-ℤ (neg-ℤ x) x y)) ∙ ( ( ap (add-ℤ' y) (left-inverse-law-add-ℤ x)) ∙ ( left-unit-law-add-ℤ y)))) equiv-add-ℤ : ℤ → (ℤ ≃ ℤ) equiv-add-ℤ x = pair (add-ℤ x) (is-equiv-add-ℤ x) -- We show that add-ℤ' y is an equivalence abstract is-equiv-add-ℤ' : (y : ℤ) → is-equiv (add-ℤ' y) is-equiv-add-ℤ' y = pair ( pair ( add-ℤ' (neg-ℤ y)) ( λ x → ( associative-add-ℤ x (neg-ℤ y) y) ∙ ( ( ap (add-ℤ x) (left-inverse-law-add-ℤ y)) ∙ ( right-unit-law-add-ℤ x)))) ( pair ( add-ℤ' (neg-ℤ y)) ( λ x → ( associative-add-ℤ x y (neg-ℤ y)) ∙ ( ( ap (add-ℤ x) (right-inverse-law-add-ℤ y)) ∙ ( right-unit-law-add-ℤ x)))) equiv-add-ℤ' : ℤ → (ℤ ≃ ℤ) equiv-add-ℤ' y = pair (add-ℤ' y) (is-equiv-add-ℤ' y) -- We show that neg-ℤ is an equivalence abstract is-equiv-neg-ℤ : is-equiv neg-ℤ is-equiv-neg-ℤ = pair (pair neg-ℤ neg-neg-ℤ) (pair neg-ℤ neg-neg-ℤ) equiv-neg-ℤ : ℤ ≃ ℤ equiv-neg-ℤ = pair neg-ℤ is-equiv-neg-ℤ -- We show that succ-Fin k is an equivalence -- We show that pred-Fin k is an equivalence -- We show that add-Fin k x is an equivalence -- We show that add-Fin' k y is an equivalence -- We show that neg-Fin k is an equivalence -- Remark 8.2.6 has-inverse : {i j : Level} {A : UU i} {B : UU j} (f : A → B) → UU (i ⊔ j) has-inverse {i} {j} {A} {B} f = Σ (B → A) (λ g → ((f ∘ g) ~ id) × ((g ∘ f) ~ id)) -- Proposition 8.2.7 is-equiv-has-inverse' : {i j : Level} {A : UU i} {B : UU j} {f : A → B} → has-inverse f → is-equiv f is-equiv-has-inverse' (pair g (pair H K)) = pair (pair g H) (pair g K) is-equiv-has-inverse : {i j : Level} {A : UU i} {B : UU j} {f : A → B} → (g : B → A) (H : (f ∘ g) ~ id) (K : (g ∘ f) ~ id) → is-equiv f is-equiv-has-inverse g H K = is-equiv-has-inverse' (pair g (pair H K)) -- Corollary 8.2.8 htpy-section-retraction : { i j : Level} {A : UU i} {B : UU j} {f : A → B} ( is-equiv-f : is-equiv f) → ( (pr1 (pr1 is-equiv-f))) ~ (pr1 (pr2 is-equiv-f)) htpy-section-retraction {i} {j} {A} {B} {f} (pair (pair g G) (pair h H)) = (htpy-inv (H ·r g)) ∙h (h ·l G) has-inverse-is-equiv : {i j : Level} {A : UU i} {B : UU j} {f : A → B} → is-equiv f → has-inverse f has-inverse-is-equiv {i} {j} {A} {B} {f} (pair (pair g G) (pair h H)) = let is-equiv-f = pair (pair g G) (pair h H) in pair g (pair G (((htpy-section-retraction is-equiv-f) ·r f) ∙h H)) inv-is-equiv : {i j : Level} {A : UU i} {B : UU j} {f : A → B} → is-equiv f → B → A inv-is-equiv is-equiv-f = pr1 (has-inverse-is-equiv is-equiv-f) issec-inv-is-equiv : {i j : Level} {A : UU i} {B : UU j} {f : A → B} → (is-equiv-f : is-equiv f) → (f ∘ (inv-is-equiv is-equiv-f)) ~ id issec-inv-is-equiv is-equiv-f = pr1 (pr2 (has-inverse-is-equiv is-equiv-f)) isretr-inv-is-equiv : {i j : Level} {A : UU i} {B : UU j} {f : A → B} → (is-equiv-f : is-equiv f) → ((inv-is-equiv is-equiv-f) ∘ f) ~ id isretr-inv-is-equiv is-equiv-f = pr2 (pr2 (has-inverse-is-equiv is-equiv-f)) is-equiv-inv-is-equiv : {i j : Level} {A : UU i} {B : UU j} {f : A → B} → (is-equiv-f : is-equiv f) → is-equiv (inv-is-equiv is-equiv-f) is-equiv-inv-is-equiv {i} {j} {A} {B} {f} is-equiv-f = is-equiv-has-inverse f ( isretr-inv-is-equiv is-equiv-f) ( issec-inv-is-equiv is-equiv-f) inv-map-equiv : {i j : Level} {A : UU i} {B : UU j} → (A ≃ B) → (B → A) inv-map-equiv e = inv-is-equiv (is-equiv-map-equiv e) issec-inv-map-equiv : {i j : Level} {A : UU i} {B : UU j} (e : A ≃ B) → ((map-equiv e) ∘ (inv-map-equiv e)) ~ id issec-inv-map-equiv e = issec-inv-is-equiv (is-equiv-map-equiv e) isretr-inv-map-equiv : {i j : Level} {A : UU i} {B : UU j} (e : A ≃ B) → ((inv-map-equiv e) ∘ (map-equiv e)) ~ id isretr-inv-map-equiv e = isretr-inv-is-equiv (is-equiv-map-equiv e) is-equiv-inv-map-equiv : {i j : Level} {A : UU i} {B : UU j} (e : A ≃ B) → is-equiv (inv-map-equiv e) is-equiv-inv-map-equiv e = is-equiv-inv-is-equiv (is-equiv-map-equiv e) inv-equiv : {i j : Level} {A : UU i} {B : UU j} → (A ≃ B) → (B ≃ A) inv-equiv e = pair (inv-map-equiv e) (is-equiv-inv-map-equiv e) -- Section 8.3 The identity type of a Σ-type -- Definition 8.3.1 Eq-Σ : {i j : Level} {A : UU i} {B : A → UU j} (s t : Σ A B) → UU (i ⊔ j) Eq-Σ {B = B} s t = Σ (Id (pr1 s) (pr1 t)) (λ α → Id (tr B α (pr2 s)) (pr2 t)) -- Lemma 8.3.2 reflexive-Eq-Σ : {i j : Level} {A : UU i} {B : A → UU j} (s : Σ A B) → Eq-Σ s s reflexive-Eq-Σ (pair a b) = pair refl refl -- Definition 8.3.3 pair-eq : {i j : Level} {A : UU i} {B : A → UU j} {s t : Σ A B} → (Id s t) → Eq-Σ s t pair-eq {s = s} refl = reflexive-Eq-Σ s -- Theorem 8.3.4 eq-pair : {i j : Level} {A : UU i} {B : A → UU j} {s t : Σ A B} → (α : Id (pr1 s) (pr1 t)) → Id (tr B α (pr2 s)) (pr2 t) → Id s t eq-pair {B = B} {pair x y} {pair .x .y} refl refl = refl eq-pair' : {i j : Level} {A : UU i} {B : A → UU j} {s t : Σ A B} → Eq-Σ s t → Id s t eq-pair' (pair α β) = eq-pair α β isretr-pair-eq : {i j : Level} {A : UU i} {B : A → UU j} (s t : Σ A B) → ((pair-eq {s = s} {t}) ∘ (eq-pair' {s = s} {t})) ~ id {A = Eq-Σ s t} isretr-pair-eq (pair x y) (pair .x .y) (pair refl refl) = refl issec-pair-eq : {i j : Level} {A : UU i} {B : A → UU j} (s t : Σ A B) → ((eq-pair' {s = s} {t}) ∘ (pair-eq {s = s} {t})) ~ id issec-pair-eq (pair x y) .(pair x y) refl = refl abstract is-equiv-eq-pair : {i j : Level} {A : UU i} {B : A → UU j} (s t : Σ A B) → is-equiv (eq-pair' {s = s} {t}) is-equiv-eq-pair s t = is-equiv-has-inverse ( pair-eq) ( issec-pair-eq s t) ( isretr-pair-eq s t) abstract is-equiv-pair-eq : {i j : Level} {A : UU i} {B : A → UU j} (s t : Σ A B) → is-equiv (pair-eq {s = s} {t}) is-equiv-pair-eq s t = is-equiv-has-inverse ( eq-pair') ( isretr-pair-eq s t) ( issec-pair-eq s t) η-pair : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} (t : Σ A B) → Id (pair (pr1 t) (pr2 t)) t η-pair t = eq-pair refl refl {- For our convenience, we repeat the above argument for cartesian products. -} Eq-prod : {i j : Level} {A : UU i} {B : UU j} (s t : A × B) → UU (i ⊔ j) Eq-prod s t = (Id (pr1 s) (pr1 t)) × (Id (pr2 s) (pr2 t)) {- We also define a function eq-pair-triv, which is like eq-pair but simplified for the case where B is just a type. -} eq-pair-triv' : {i j : Level} {A : UU i} {B : UU j} (s t : prod A B) → Eq-prod s t → Id s t eq-pair-triv' (pair x y) (pair .x .y) (pair refl refl) = refl eq-pair-triv : {i j : Level} {A : UU i} {B : UU j} {s t : prod A B} → Eq-prod s t → Id s t eq-pair-triv {s = s} {t} = eq-pair-triv' s t {- Ideally, we would use the 3-for-2 property of equivalences to show that eq-pair-triv is an equivalence, using that eq-pair is an equivalence. Indeed, there is an equivalence (Id x x') × (Id y y') → Σ (Id x x') (λ p → Id (tr (λ x → B) p y) y'). However, to show that this map is an equivalence we either give a direct proof (in which case we might as well have given a direct proof that eq-pair-triv is an equivalence), or we use the fact that it is the induced map on total spaces of a fiberwise equivalence (the topic of Lecture 8). Thus it seems that a direct proof showing that eq-pair-triv is an equivalence is quickest for now. -} pair-eq-triv' : {i j : Level} {A : UU i} {B : UU j} (s t : prod A B) → Id s t → Eq-prod s t pair-eq-triv' s t α = pair (ap pr1 α) (ap pr2 α) isretr-pair-eq-triv' : {i j : Level} {A : UU i} {B : UU j} (s t : prod A B) → ((pair-eq-triv' s t) ∘ (eq-pair-triv' s t)) ~ id isretr-pair-eq-triv' (pair x y) (pair .x .y) (pair refl refl) = refl issec-pair-eq-triv' : {i j : Level} {A : UU i} {B : UU j} (s t : prod A B) → ((eq-pair-triv' s t) ∘ (pair-eq-triv' s t)) ~ id issec-pair-eq-triv' (pair x y) (pair .x .y) refl = refl abstract is-equiv-eq-pair-triv' : {i j : Level} {A : UU i} {B : UU j} (s t : prod A B) → is-equiv (eq-pair-triv' s t) is-equiv-eq-pair-triv' s t = is-equiv-has-inverse ( pair-eq-triv' s t) ( issec-pair-eq-triv' s t) ( isretr-pair-eq-triv' s t) -- Exercises -- Exercise 8.1 {- We show that inv is an equivalence. -} inv-inv : {i : Level} {A : UU i} {x y : A} (p : Id x y) → Id (inv (inv p)) p inv-inv refl = refl abstract is-equiv-inv : {i : Level} {A : UU i} (x y : A) → is-equiv (λ (p : Id x y) → inv p) is-equiv-inv x y = is-equiv-has-inverse inv inv-inv inv-inv equiv-inv : {i : Level} {A : UU i} (x y : A) → (Id x y) ≃ (Id y x) equiv-inv x y = pair inv (is-equiv-inv x y) {- We show that concat p is an equivalence, for any path p. -} inv-concat : {i : Level} {A : UU i} {x y : A} (p : Id x y) (z : A) → (Id x z) → (Id y z) inv-concat p = concat (inv p) isretr-inv-concat : {i : Level} {A : UU i} {x y : A} (p : Id x y) (z : A) → ((inv-concat p z) ∘ (concat p z)) ~ id isretr-inv-concat refl z q = refl issec-inv-concat : {i : Level} {A : UU i} {x y : A} (p : Id x y) (z : A) → ((concat p z) ∘ (inv-concat p z)) ~ id issec-inv-concat refl z refl = refl abstract is-equiv-concat : {i : Level} {A : UU i} {x y : A} (p : Id x y) (z : A) → is-equiv (concat p z) is-equiv-concat p z = is-equiv-has-inverse ( inv-concat p z) ( issec-inv-concat p z) ( isretr-inv-concat p z) equiv-concat : {i : Level} {A : UU i} {x y : A} (p : Id x y) (z : A) → Id y z ≃ Id x z equiv-concat p z = pair (concat p z) (is-equiv-concat p z) {- We show that concat' q is an equivalence, for any path q. -} concat' : {i : Level} {A : UU i} (x : A) {y z : A} → Id y z → Id x y → Id x z concat' x q p = p ∙ q inv-concat' : {i : Level} {A : UU i} (x : A) {y z : A} → Id y z → Id x z → Id x y inv-concat' x q = concat' x (inv q) isretr-inv-concat' : {i : Level} {A : UU i} (x : A) {y z : A} (q : Id y z) → ((inv-concat' x q) ∘ (concat' x q)) ~ id isretr-inv-concat' x refl refl = refl issec-inv-concat' : {i : Level} {A : UU i} (x : A) {y z : A} (q : Id y z) → ((concat' x q) ∘ (inv-concat' x q)) ~ id issec-inv-concat' x refl refl = refl abstract is-equiv-concat' : {i : Level} {A : UU i} (x : A) {y z : A} (q : Id y z) → is-equiv (concat' x q) is-equiv-concat' x q = is-equiv-has-inverse ( inv-concat' x q) ( issec-inv-concat' x q) ( isretr-inv-concat' x q) equiv-concat' : {i : Level} {A : UU i} (x : A) {y z : A} (q : Id y z) → Id x y ≃ Id x z equiv-concat' x q = pair (concat' x q) (is-equiv-concat' x q) {- We show that tr B p is an equivalence, for an path p and any type family B. -} inv-tr : {i j : Level} {A : UU i} (B : A → UU j) {x y : A} → Id x y → B y → B x inv-tr B p = tr B (inv p) isretr-inv-tr : {i j : Level} {A : UU i} (B : A → UU j) {x y : A} (p : Id x y) → ((inv-tr B p ) ∘ (tr B p)) ~ id isretr-inv-tr B refl b = refl issec-inv-tr : {i j : Level} {A : UU i} (B : A → UU j) {x y : A} (p : Id x y) → ((tr B p) ∘ (inv-tr B p)) ~ id issec-inv-tr B refl b = refl abstract is-equiv-tr : {i j : Level} {A : UU i} (B : A → UU j) {x y : A} (p : Id x y) → is-equiv (tr B p) is-equiv-tr B p = is-equiv-has-inverse ( inv-tr B p) ( issec-inv-tr B p) ( isretr-inv-tr B p) equiv-tr : {i j : Level} {A : UU i} (B : A → UU j) {x y : A} (p : Id x y) → (B x) ≃ (B y) equiv-tr B p = pair (tr B p) (is-equiv-tr B p) -- Exercise 8.2 abstract not-equiv-const : (b : bool) → ¬ (is-equiv (const bool bool b)) not-equiv-const true (pair (pair s issec) (pair r isretr)) = neq-false-true-𝟚 (inv (issec false)) not-equiv-const false (pair (pair s issec) (pair r isretr)) = neq-false-true-𝟚 (issec true) -- Exercise 8.3 -- Exercise 8.3(a) abstract is-equiv-htpy : {i j : Level} {A : UU i} {B : UU j} {f : A → B} (g : A → B) → f ~ g → is-equiv g → is-equiv f is-equiv-htpy g H (pair (pair gs issec) (pair gr isretr)) = pair ( pair gs ((H ·r gs) ∙h issec)) ( pair gr ((gr ·l H) ∙h isretr)) abstract is-equiv-htpy' : {i j : Level} {A : UU i} {B : UU j} (f : A → B) {g : A → B} → f ~ g → is-equiv f → is-equiv g is-equiv-htpy' f H = is-equiv-htpy f (htpy-inv H) -- Exercise 8.3(b) htpy-inv-is-equiv : {i j : Level} {A : UU i} {B : UU j} {f f' : A → B} (H : f ~ f') → (is-equiv-f : is-equiv f) (is-equiv-f' : is-equiv f') → (inv-is-equiv is-equiv-f) ~ (inv-is-equiv is-equiv-f') htpy-inv-is-equiv H is-equiv-f is-equiv-f' b = ( inv (isretr-inv-is-equiv is-equiv-f' (inv-is-equiv is-equiv-f b))) ∙ ( ap (inv-is-equiv is-equiv-f') ( ( inv (H (inv-is-equiv is-equiv-f b))) ∙ ( issec-inv-is-equiv is-equiv-f b))) -- Exercise 8.4 -- Exercise 8.4(a) {- Exercise 8.4 (a) asks to show that, given a commuting triangle f ~ g ∘ h and a section s of h, we get a new commuting triangle g ~ f ∘ s. Moreover, under the same assumptions it follows that f has a section if and only if g has a section. -} triangle-section : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) (S : sec h) → g ~ (f ∘ (pr1 S)) triangle-section f g h H (pair s issec) = htpy-inv (( H ·r s) ∙h (g ·l issec)) section-comp : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → sec h → sec f → sec g section-comp f g h H sec-h sec-f = pair (h ∘ (pr1 sec-f)) ((htpy-inv (H ·r (pr1 sec-f))) ∙h (pr2 sec-f)) section-comp' : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → sec h → sec g → sec f section-comp' f g h H sec-h sec-g = pair ( (pr1 sec-h) ∘ (pr1 sec-g)) ( ( H ·r ((pr1 sec-h) ∘ (pr1 sec-g))) ∙h ( ( g ·l ((pr2 sec-h) ·r (pr1 sec-g))) ∙h ((pr2 sec-g)))) -- Exercise 8.4(b) {- Exercise 8.4 (b) is dual to exercise 8.4 (a). It asks to show that, given a commuting triangle f ~ g ∘ h and a retraction r of g, we get a new commuting triangle h ~ r ∘ f. Moreover, under these assumptions it also follows that f has a retraction if and only if h has a retraction. -} triangle-retraction : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) (R : retr g) → h ~ ((pr1 R) ∘ f) triangle-retraction f g h H (pair r isretr) = htpy-inv (( r ·l H) ∙h (isretr ·r h)) retraction-comp : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → retr g → retr f → retr h retraction-comp f g h H retr-g retr-f = pair ( (pr1 retr-f) ∘ g) ( (htpy-inv ((pr1 retr-f) ·l H)) ∙h (pr2 retr-f)) retraction-comp' : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → retr g → retr h → retr f retraction-comp' f g h H retr-g retr-h = pair ( (pr1 retr-h) ∘ (pr1 retr-g)) ( ( ((pr1 retr-h) ∘ (pr1 retr-g)) ·l H) ∙h ( ((pr1 retr-h) ·l ((pr2 retr-g) ·r h)) ∙h (pr2 retr-h))) -- Exercise 8.4(c) {- In Exercise 8.4 (c) we use the constructions of parts (a) and (b) to derive the 3-for-2 property of equivalences. -} abstract is-equiv-comp : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → is-equiv h → is-equiv g → is-equiv f is-equiv-comp f g h H (pair sec-h retr-h) (pair sec-g retr-g) = pair ( section-comp' f g h H sec-h sec-g) ( retraction-comp' f g h H retr-g retr-h) abstract is-equiv-comp' : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (g : B → X) (h : A → B) → is-equiv h → is-equiv g → is-equiv (g ∘ h) is-equiv-comp' g h = is-equiv-comp (g ∘ h) g h refl-htpy equiv-comp : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} → (B ≃ X) → (A ≃ B) → (A ≃ X) equiv-comp g h = pair ((pr1 g) ∘ (pr1 h)) (is-equiv-comp' (pr1 g) (pr1 h) (pr2 h) (pr2 g)) _∘e_ : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} → (B ≃ X) → (A ≃ B) → (A ≃ X) _∘e_ = equiv-comp abstract is-equiv-left-factor : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → is-equiv f → is-equiv h → is-equiv g is-equiv-left-factor f g h H ( pair sec-f retr-f) ( pair (pair sh sh-issec) retr-h) = pair ( section-comp f g h H (pair sh sh-issec) sec-f) ( retraction-comp' g f sh ( triangle-section f g h H (pair sh sh-issec)) ( retr-f) ( pair h sh-issec)) abstract is-equiv-left-factor' : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (g : B → X) (h : A → B) → is-equiv (g ∘ h) → is-equiv h → is-equiv g is-equiv-left-factor' g h = is-equiv-left-factor (g ∘ h) g h refl-htpy abstract is-equiv-right-factor : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (f : A → X) (g : B → X) (h : A → B) (H : f ~ (g ∘ h)) → is-equiv g → is-equiv f → is-equiv h is-equiv-right-factor f g h H ( pair sec-g (pair rg rg-isretr)) ( pair sec-f retr-f) = pair ( section-comp' h rg f ( triangle-retraction f g h H (pair rg rg-isretr)) ( sec-f) ( pair g rg-isretr)) ( retraction-comp f g h H (pair rg rg-isretr) retr-f) abstract is-equiv-right-factor' : {i j k : Level} {A : UU i} {B : UU j} {X : UU k} (g : B → X) (h : A → B) → is-equiv g → is-equiv (g ∘ h) → is-equiv h is-equiv-right-factor' g h = is-equiv-right-factor (g ∘ h) g h refl-htpy abstract is-equiv-is-section-is-equiv : {i j : Level} {A : UU i} {B : UU j} {f : A → B} {g : B → A} → is-equiv f → (f ∘ g) ~ id → is-equiv g is-equiv-is-section-is-equiv {B = B} {f = f} {g = g} is-equiv-f H = is-equiv-right-factor id f g (htpy-inv H) is-equiv-f (is-equiv-id B) abstract is-equiv-is-retraction-is-equiv : {i j : Level} {A : UU i} {B : UU j} {f : A → B} {g : B → A} → is-equiv f → (g ∘ f) ~ id → is-equiv g is-equiv-is-retraction-is-equiv {A = A} {f = f} {g = g} is-equiv-f H = is-equiv-left-factor id g f (htpy-inv H) (is-equiv-id A) is-equiv-f -- Exercise 8.5 -- Exercise 8.5 (a) -- Exercise 8.5 (b) {- We prove the left unit law for coproducts. -} inv-inr-coprod-empty : {l : Level} (X : UU l) → coprod empty X → X inv-inr-coprod-empty X (inr x) = x issec-inv-inr-coprod-empty : {l : Level} (X : UU l) → (inr ∘ (inv-inr-coprod-empty X)) ~ id issec-inv-inr-coprod-empty X (inr x) = refl isretr-inv-inr-coprod-empty : {l : Level} (X : UU l) → ((inv-inr-coprod-empty X) ∘ inr) ~ id isretr-inv-inr-coprod-empty X x = refl is-equiv-inr-coprod-empty : {l : Level} (X : UU l) → is-equiv (inr {A = empty} {B = X}) is-equiv-inr-coprod-empty X = is-equiv-has-inverse ( inv-inr-coprod-empty X) ( issec-inv-inr-coprod-empty X) ( isretr-inv-inr-coprod-empty X) left-unit-law-coprod : {l : Level} (X : UU l) → X ≃ (coprod empty X) left-unit-law-coprod X = pair inr (is-equiv-inr-coprod-empty X) {- We prove the right unit law for coproducts. -} inv-inl-coprod-empty : {l : Level} (X : UU l) → (coprod X empty) → X inv-inl-coprod-empty X (inl x) = x issec-inv-inl-coprod-empty : {l : Level} (X : UU l) → (inl ∘ (inv-inl-coprod-empty X)) ~ id issec-inv-inl-coprod-empty X (inl x) = refl isretr-inv-inl-coprod-empty : {l : Level} (X : UU l) → ((inv-inl-coprod-empty X) ∘ inl) ~ id isretr-inv-inl-coprod-empty X x = refl is-equiv-inl-coprod-empty : {l : Level} (X : UU l) → is-equiv (inl {A = X} {B = empty}) is-equiv-inl-coprod-empty X = is-equiv-has-inverse ( inv-inl-coprod-empty X) ( issec-inv-inl-coprod-empty X) ( isretr-inv-inl-coprod-empty X) right-unit-law-coprod : {l : Level} (X : UU l) → X ≃ (coprod X empty) right-unit-law-coprod X = pair inl (is-equiv-inl-coprod-empty X) {- We prove a left zero law for cartesian products. -} inv-pr1-prod-empty : {l : Level} (X : UU l) → empty → empty × X inv-pr1-prod-empty X () issec-inv-pr1-prod-empty : {l : Level} (X : UU l) → (pr1 ∘ (inv-pr1-prod-empty X)) ~ id issec-inv-pr1-prod-empty X () isretr-inv-pr1-prod-empty : {l : Level} (X : UU l) → ((inv-pr1-prod-empty X) ∘ pr1) ~ id isretr-inv-pr1-prod-empty X (pair () x) is-equiv-pr1-prod-empty : {l : Level} (X : UU l) → is-equiv (pr1 {A = empty} {B = λ t → X}) is-equiv-pr1-prod-empty X = is-equiv-has-inverse ( inv-pr1-prod-empty X) ( issec-inv-pr1-prod-empty X) ( isretr-inv-pr1-prod-empty X) left-zero-law-prod : {l : Level} (X : UU l) → (empty × X) ≃ empty left-zero-law-prod X = pair pr1 (is-equiv-pr1-prod-empty X) {- We prove the right zero law for cartesian products. -} inv-pr2-prod-empty : {l : Level} (X : UU l) → empty → (X × empty) inv-pr2-prod-empty X () issec-inv-pr2-prod-empty : {l : Level} (X : UU l) → (pr2 ∘ (inv-pr2-prod-empty X)) ~ id issec-inv-pr2-prod-empty X () isretr-inv-pr2-prod-empty : {l : Level} (X : UU l) → ((inv-pr2-prod-empty X) ∘ pr2) ~ id isretr-inv-pr2-prod-empty X (pair x ()) is-equiv-pr2-prod-empty : {l : Level} (X : UU l) → is-equiv (pr2 {A = X} {B = λ x → empty}) is-equiv-pr2-prod-empty X = is-equiv-has-inverse ( inv-pr2-prod-empty X) ( issec-inv-pr2-prod-empty X) ( isretr-inv-pr2-prod-empty X) right-zero-law-prod : {l : Level} (X : UU l) → (X × empty) ≃ empty right-zero-law-prod X = pair pr2 (is-equiv-pr2-prod-empty X) -- Exercise 7.5 -- Exercise 7.5(a) -- Exercise 7.5(c) -- Exercise 7.6 -- Exercise 7.7 {- In this exercise we construct an equivalence from A + B to B + A, showing that the coproduct is commutative. -} swap-coprod : {i j : Level} (A : UU i) (B : UU j) → coprod A B → coprod B A swap-coprod A B (inl x) = inr x swap-coprod A B (inr x) = inl x swap-swap-coprod : {i j : Level} (A : UU i) (B : UU j) → ((swap-coprod B A) ∘ (swap-coprod A B)) ~ id swap-swap-coprod A B (inl x) = refl swap-swap-coprod A B (inr x) = refl abstract is-equiv-swap-coprod : {i j : Level} (A : UU i) (B : UU j) → is-equiv (swap-coprod A B) is-equiv-swap-coprod A B = is-equiv-has-inverse ( swap-coprod B A) ( swap-swap-coprod B A) ( swap-swap-coprod A B) equiv-swap-coprod : {i j : Level} (A : UU i) (B : UU j) → coprod A B ≃ coprod B A equiv-swap-coprod A B = pair (swap-coprod A B) (is-equiv-swap-coprod A B) swap-prod : {i j : Level} (A : UU i) (B : UU j) → prod A B → prod B A swap-prod A B t = pair (pr2 t) (pr1 t) swap-swap-prod : {i j : Level} (A : UU i) (B : UU j) → ((swap-prod B A) ∘ (swap-prod A B)) ~ id swap-swap-prod A B (pair x y) = refl abstract is-equiv-swap-prod : {i j : Level} (A : UU i) (B : UU j) → is-equiv (swap-prod A B) is-equiv-swap-prod A B = is-equiv-has-inverse ( swap-prod B A) ( swap-swap-prod B A) ( swap-swap-prod A B) equiv-swap-prod : {i j : Level} (A : UU i) (B : UU j) → (A × B) ≃ (B × A) equiv-swap-prod A B = pair (swap-prod A B) (is-equiv-swap-prod A B) -- Exercise 7.8 {- In this exercise we show that if A is a retract of B, then so are its identity types. -} ap-retraction : {i j : Level} {A : UU i} {B : UU j} (i : A → B) (r : B → A) (H : (r ∘ i) ~ id) (x y : A) → Id (i x) (i y) → Id x y ap-retraction i r H x y p = ( inv (H x)) ∙ ((ap r p) ∙ (H y)) isretr-ap-retraction : {i j : Level} {A : UU i} {B : UU j} (i : A → B) (r : B → A) (H : (r ∘ i) ~ id) (x y : A) → ((ap-retraction i r H x y) ∘ (ap i {x} {y})) ~ id isretr-ap-retraction i r H x .x refl = left-inv (H x) retr-ap : {i j : Level} {A : UU i} {B : UU j} (i : A → B) → retr i → (x y : A) → retr (ap i {x} {y}) retr-ap i (pair r H) x y = pair (ap-retraction i r H x y) (isretr-ap-retraction i r H x y) Id-retract-of-Id : {i j : Level} {A : UU i} {B : UU j} (R : A retract-of B) → (x y : A) → (Id x y) retract-of (Id (pr1 R x) (pr1 R y)) Id-retract-of-Id (pair i (pair r H)) x y = pair ( ap i {x} {y}) ( retr-ap i (pair r H) x y) -- Exercise 7.9 Σ-assoc : {i j k : Level} (A : UU i) (B : A → UU j) (C : (Σ A B) → UU k) → Σ (Σ A B) C → Σ A (λ x → Σ (B x) (λ y → C (pair x y))) Σ-assoc A B C (pair (pair x y) z) = pair x (pair y z) Σ-assoc' : {i j k : Level} (A : UU i) (B : A → UU j) (C : (Σ A B) → UU k) → Σ A (λ x → Σ (B x) (λ y → C (pair x y))) → Σ (Σ A B) C Σ-assoc' A B C t = pair (pair (pr1 t) (pr1 (pr2 t))) (pr2 (pr2 t)) Σ-assoc-assoc : {i j k : Level} (A : UU i) (B : A → UU j) (C : (Σ A B) → UU k) → ((Σ-assoc' A B C) ∘ (Σ-assoc A B C)) ~ id Σ-assoc-assoc A B C (pair (pair x y) z) = refl Σ-assoc-assoc' : {i j k : Level} (A : UU i) (B : A → UU j) (C : (Σ A B) → UU k) → ((Σ-assoc A B C) ∘ (Σ-assoc' A B C)) ~ id Σ-assoc-assoc' A B C (pair x (pair y z)) = refl abstract is-equiv-Σ-assoc : {i j k : Level} (A : UU i) (B : A → UU j) (C : (Σ A B) → UU k) → is-equiv (Σ-assoc A B C) is-equiv-Σ-assoc A B C = is-equiv-has-inverse ( Σ-assoc' A B C) ( Σ-assoc-assoc' A B C) ( Σ-assoc-assoc A B C) equiv-Σ-assoc : {i j k : Level} (A : UU i) (B : A → UU j) (C : (Σ A B) → UU k) → Σ (Σ A B) C ≃ Σ A (λ x → Σ (B x) (λ y → C (pair x y))) equiv-Σ-assoc A B C = pair (Σ-assoc A B C) (is-equiv-Σ-assoc A B C) -- Exercise 7.10 Σ-swap : {i j k : Level} (A : UU i) (B : UU j) (C : A → B → UU k) → Σ A (λ x → Σ B (C x)) → Σ B (λ y → Σ A (λ x → C x y)) Σ-swap A B C t = pair (pr1 (pr2 t)) (pair (pr1 t) (pr2 (pr2 t))) Σ-swap' : {i j k : Level} (A : UU i) (B : UU j) (C : A → B → UU k) → Σ B (λ y → Σ A (λ x → C x y)) → Σ A (λ x → Σ B (C x)) Σ-swap' A B C = Σ-swap B A (λ y x → C x y) Σ-swap-swap : {i j k : Level} (A : UU i) (B : UU j) (C : A → B → UU k) → ((Σ-swap' A B C) ∘ (Σ-swap A B C)) ~ id Σ-swap-swap A B C (pair x (pair y z)) = refl abstract is-equiv-Σ-swap : {i j k : Level} (A : UU i) (B : UU j) (C : A → B → UU k) → is-equiv (Σ-swap A B C) is-equiv-Σ-swap A B C = is-equiv-has-inverse ( Σ-swap' A B C) ( Σ-swap-swap B A (λ y x → C x y)) ( Σ-swap-swap A B C) -- Exercise 7.11 abstract is-equiv-add-ℤ-right : (x : ℤ) → is-equiv (add-ℤ x) is-equiv-add-ℤ-right x = is-equiv-has-inverse ( add-ℤ (neg-ℤ x)) ( λ y → ( inv (associative-add-ℤ x (neg-ℤ x) y)) ∙ ( ap (λ t → add-ℤ t y) (right-inverse-law-add-ℤ x))) ( λ y → ( inv (associative-add-ℤ (neg-ℤ x) x y)) ∙ ( ap (λ t → add-ℤ t y) (left-inverse-law-add-ℤ x))) abstract is-equiv-add-ℤ-left : (y : ℤ) → is-equiv (λ x → add-ℤ x y) is-equiv-add-ℤ-left y = is-equiv-htpy (add-ℤ y) ( λ x → commutative-add-ℤ x y) ( is-equiv-add-ℤ-right y) -- Exercise 7.12 -- Exercise 7.13 {- We construct the functoriality of coproducts. -} htpy-functor-coprod : {l1 l2 l1' l2' : Level} {A : UU l1} {B : UU l2} {A' : UU l1'} {B' : UU l2'} {f f' : A → A'} (H : f ~ f') {g g' : B → B'} (K : g ~ g') → (functor-coprod f g) ~ (functor-coprod f' g') htpy-functor-coprod H K (inl x) = ap inl (H x) htpy-functor-coprod H K (inr y) = ap inr (K y) id-functor-coprod : {l1 l2 : Level} (A : UU l1) (B : UU l2) → (functor-coprod (id {A = A}) (id {A = B})) ~ id id-functor-coprod A B (inl x) = refl id-functor-coprod A B (inr x) = refl compose-functor-coprod : {l1 l2 l1' l2' l1'' l2'' : Level} {A : UU l1} {B : UU l2} {A' : UU l1'} {B' : UU l2'} {A'' : UU l1''} {B'' : UU l2''} (f : A → A') (f' : A' → A'') (g : B → B') (g' : B' → B'') → (functor-coprod (f' ∘ f) (g' ∘ g)) ~ ((functor-coprod f' g') ∘ (functor-coprod f g)) compose-functor-coprod f f' g g' (inl x) = refl compose-functor-coprod f f' g g' (inr y) = refl abstract is-equiv-functor-coprod : {l1 l2 l1' l2' : Level} {A : UU l1} {B : UU l2} {A' : UU l1'} {B' : UU l2'} {f : A → A'} {g : B → B'} → is-equiv f → is-equiv g → is-equiv (functor-coprod f g) is-equiv-functor-coprod {A = A} {B = B} {A' = A'} {B' = B'} {f = f} {g = g} (pair (pair sf issec-sf) (pair rf isretr-rf)) (pair (pair sg issec-sg) (pair rg isretr-rg)) = pair ( pair ( functor-coprod sf sg) ( ( ( htpy-inv (compose-functor-coprod sf f sg g)) ∙h ( htpy-functor-coprod issec-sf issec-sg)) ∙h ( id-functor-coprod A' B'))) ( pair ( functor-coprod rf rg) ( ( ( htpy-inv (compose-functor-coprod f rf g rg)) ∙h ( htpy-functor-coprod isretr-rf isretr-rg)) ∙h ( id-functor-coprod A B))) equiv-functor-coprod : {l1 l2 l1' l2' : Level} {A : UU l1} {B : UU l2} {A' : UU l1'} {B' : UU l2'} → (A ≃ A') → (B ≃ B') → ((coprod A B) ≃ (coprod A' B')) equiv-functor-coprod (pair e is-equiv-e) (pair f is-equiv-f) = pair ( functor-coprod e f) ( is-equiv-functor-coprod is-equiv-e is-equiv-f) -- Extra material abstract is-equiv-inv-con : {i : Level} {A : UU i} {x y z : A} (p : Id x y) (q : Id y z) (r : Id x z) → is-equiv (inv-con p q r) is-equiv-inv-con refl q r = is-equiv-id (Id q r) equiv-inv-con : {i : Level} {A : UU i} {x y z : A} (p : Id x y) (q : Id y z) (r : Id x z) → Id (p ∙ q) r ≃ Id q ((inv p) ∙ r) equiv-inv-con p q r = pair (inv-con p q r) (is-equiv-inv-con p q r) abstract is-equiv-con-inv : {i : Level} {A : UU i} {x y z : A} (p : Id x y) (q : Id y z) (r : Id x z) → is-equiv (con-inv p q r) is-equiv-con-inv p refl r = is-equiv-comp' ( concat' p (inv right-unit)) ( concat (inv right-unit) r) ( is-equiv-concat (inv right-unit) r) ( is-equiv-concat' p (inv right-unit)) equiv-con-inv : {i : Level} {A : UU i} {x y z : A} (p : Id x y) (q : Id y z) (r : Id x z) → Id (p ∙ q) r ≃ Id p (r ∙ (inv q)) equiv-con-inv p q r = pair (con-inv p q r) (is-equiv-con-inv p q r) -- Extra constructions with homotopies htpy-inv-con : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} {f g h : (x : A) → B x} → (H : f ~ g) (K : g ~ h) (L : f ~ h) → (H ∙h K) ~ L → K ~ ((htpy-inv H) ∙h L) htpy-inv-con H K L M x = inv-con (H x) (K x) (L x) (M x) htpy-con-inv : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} {f g h : (x : A) → B x} → (H : f ~ g) (K : g ~ h) (L : f ~ h) → (H ∙h K) ~ L → H ~ (L ∙h (htpy-inv K)) htpy-con-inv H K L M x = con-inv (H x) (K x) (L x) (M x) htpy-ap-concat : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} {f g h : (x : A) → B x} → (H : f ~ g) (K K' : g ~ h) → K ~ K' → (H ∙h K) ~ (H ∙h K') htpy-ap-concat {g = g} {h} H K K' L x = ap (concat (H x) (h x)) (L x) htpy-ap-concat' : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} {f g h : (x : A) → B x} → (H H' : f ~ g) (K : g ~ h) → H ~ H' → (H ∙h K) ~ (H' ∙h K) htpy-ap-concat' H H' K L x = ap (concat' _ (K x)) (L x) htpy-distributive-inv-concat : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} {f g h : (x : A) → B x} → (H : f ~ g) (K : g ~ h) → (htpy-inv (H ∙h K)) ~ ((htpy-inv K) ∙h (htpy-inv H)) htpy-distributive-inv-concat H K x = distributive-inv-concat (H x) (K x) htpy-ap-inv : {l1 l2 : Level} {A : UU l1} {B : A → UU l2} {f g : (x : A) → B x} → {H H' : f ~ g} → H ~ H' → (htpy-inv H) ~ (htpy-inv H') htpy-ap-inv K x = ap inv (K x) htpy-left-whisk-htpy-inv : {l1 l2 l3 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {f f' : A → B} (g : B → C) (H : f ~ f') → (g ·l (htpy-inv H)) ~ htpy-inv (g ·l H) htpy-left-whisk-htpy-inv g H x = ap-inv g (H x) htpy-right-whisk-htpy-inv : {l1 l2 l3 : Level} {A : UU l1} {B : UU l2} {C : UU l3} {g g' : B → C} (H : g ~ g') (f : A → B) → ((htpy-inv H) ·r f) ~ (htpy-inv (H ·r f)) htpy-right-whisk-htpy-inv H f = refl-htpy -- Old stuff element : {i : Level} {A : UU i} → A → unit → A element a star = a htpy-element-constant : {i : Level} {A : UU i} (a : A) → (element a) ~ (const unit A a) htpy-element-constant a star = refl ap-const : {i j : Level} {A : UU i} {B : UU j} (b : B) (x y : A) → (ap (const A B b) {x} {y}) ~ const (Id x y) (Id b b) refl ap-const b x .x refl = refl ",16305,True,3233.6582922132325,median "------------------------------------------------------------------------ -- Lenses defined in terms of a getter, equivalences between the -- getter's ""preimages"", and a coherence property ------------------------------------------------------------------------ {-# OPTIONS --cubical #-} import Equality.Path as P module Lens.Non-dependent.Equivalent-preimages {e⁺} (eq : ∀ {a p} → P.Equality-with-paths a p e⁺) where open P.Derived-definitions-and-properties eq open import Logical-equivalence using (_⇔_) open import Prelude renaming (_∘_ to _⊚_) open import Bijection equality-with-J as B using (_↔_) open import Equality.Path.Isomorphisms eq open import Equivalence equality-with-J as Eq using (_≃_; Is-equivalence) open import Function-universe equality-with-J as F hiding (id; _∘_; ∘⁻¹≃) open import H-level equality-with-J as H-level open import H-level.Closure equality-with-J open import H-level.Truncation.Propositional eq as PT using (∥_∥; ∣_∣) open import Preimage equality-with-J using (_⁻¹_) open import Surjection equality-with-J using (_↠_) open import Univalence-axiom equality-with-J open import Lens.Non-dependent eq import Lens.Non-dependent.Higher eq as Higher import Lens.Non-dependent.Higher.Combinators eq as HC import Lens.Non-dependent.Traditional eq as Traditional private variable ℓ : Level A B C : Type ℓ a b c z : A ------------------------------------------------------------------------ -- The lens type family -- Lenses defined in terms of a getter, equivalences between the -- getter's ""preimages"", and a coherence property. -- -- This definition is based on a suggestion from Andrea Vezzosi. Note -- that the fields and some derived properties correspond to things -- discussed by Paolo Capriotti in the context of his higher lenses -- (http://homotopytypetheory.org/2014/04/29/higher-lenses/). record Lens (A : Type a) (B : Type b) : Type (a ⊔ b) where no-eta-equality pattern constructor lens field -- A getter. get : A → B -- A function from one ""preimage"" of get to another. get⁻¹-const : (b₁ b₂ : B) → get ⁻¹ b₁ → get ⁻¹ b₂ -- This function is an equivalence. get⁻¹-const-equivalence : (b₁ b₂ : B) → Is-equivalence (get⁻¹-const b₁ b₂) -- A coherence property. get⁻¹-const-∘ : (b₁ b₂ b₃ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₂ b₃ (get⁻¹-const b₁ b₂ p) ≡ get⁻¹-const b₁ b₃ p -- All the getter's ""preimages"" are equivalent. get⁻¹-constant : (b₁ b₂ : B) → get ⁻¹ b₁ ≃ get ⁻¹ b₂ get⁻¹-constant b₁ b₂ = Eq.⟨ _ , get⁻¹-const-equivalence b₁ b₂ ⟩ -- The inverse of get⁻¹-const. get⁻¹-const⁻¹ : (b₁ b₂ : B) → get ⁻¹ b₂ → get ⁻¹ b₁ get⁻¹-const⁻¹ b₁ b₂ = _≃_.from (get⁻¹-constant b₁ b₂) -- Some derived coherence properties. get⁻¹-const-id : (b : B) (p : get ⁻¹ b) → get⁻¹-const b b p ≡ p get⁻¹-const-id b p = get⁻¹-const b b p ≡⟨ sym $ _≃_.left-inverse-of (get⁻¹-constant _ _) _ ⟩ get⁻¹-const⁻¹ b b (get⁻¹-const b b (get⁻¹-const b b p)) ≡⟨ cong (get⁻¹-const⁻¹ b b) $ get⁻¹-const-∘ _ _ _ _ ⟩ get⁻¹-const⁻¹ b b (get⁻¹-const b b p) ≡⟨ _≃_.left-inverse-of (get⁻¹-constant _ _) _ ⟩∎ p ∎ get⁻¹-const-inverse : (b₁ b₂ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₁ b₂ p ≡ get⁻¹-const⁻¹ b₂ b₁ p get⁻¹-const-inverse b₁ b₂ p = sym $ _≃_.to-from (get⁻¹-constant _ _) ( get⁻¹-const b₂ b₁ (get⁻¹-const b₁ b₂ p) ≡⟨ get⁻¹-const-∘ _ _ _ _ ⟩ get⁻¹-const b₁ b₁ p ≡⟨ get⁻¹-const-id _ _ ⟩∎ p ∎) -- A setter. set : A → B → A set a b = $⟨ a , refl _ ⟩ get ⁻¹ get a ↝⟨ get⁻¹-const (get a) b ⟩ get ⁻¹ b ↝⟨ proj₁ ⟩□ A □ -- The lens laws can be proved. get-set : ∀ a b → get (set a b) ≡ b get-set a b = get (proj₁ (get⁻¹-const (get a) b (a , refl _))) ≡⟨ proj₂ (get⁻¹-const (get a) b (a , refl _)) ⟩∎ b ∎ set-get : ∀ a → set a (get a) ≡ a set-get a = proj₁ (get⁻¹-const (get a) (get a) (a , refl _)) ≡⟨ cong proj₁ $ get⁻¹-const-id _ _ ⟩∎ a ∎ set-set : ∀ a b₁ b₂ → set (set a b₁) b₂ ≡ set a b₂ set-set a b₁ b₂ = proj₁ (get⁻¹-const (get (set a b₁)) b₂ (set a b₁ , refl _)) ≡⟨ elim¹ (λ {b} eq → proj₁ (get⁻¹-const (get (set a b₁)) b₂ (set a b₁ , refl _)) ≡ proj₁ (get⁻¹-const b b₂ (set a b₁ , eq))) (refl _) (get-set a b₁) ⟩ proj₁ (get⁻¹-const b₁ b₂ (set a b₁ , get-set a b₁)) ≡⟨⟩ proj₁ (get⁻¹-const b₁ b₂ (get⁻¹-const (get a) b₁ (a , refl _))) ≡⟨ cong proj₁ $ get⁻¹-const-∘ _ _ _ _ ⟩∎ proj₁ (get⁻¹-const (get a) b₂ (a , refl _)) ∎ -- A traditional lens. traditional-lens : Traditional.Lens A B traditional-lens = record { get = get ; set = set ; get-set = get-set ; set-get = set-get ; set-set = set-set } instance -- The lenses defined above have getters and setters. has-getter-and-setter : Has-getter-and-setter (Lens {a = a} {b = b}) has-getter-and-setter = record { get = Lens.get ; set = Lens.set } -- The record type above is equivalent to a nested Σ-type. Lens-as-Σ : Lens A B ≃ ∃ λ (get : A → B) → ∃ λ (get⁻¹-const : (b₁ b₂ : B) → get ⁻¹ b₁ → get ⁻¹ b₂) → ((b₁ b₂ : B) → Is-equivalence (get⁻¹-const b₁ b₂)) × ((b₁ b₂ b₃ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₂ b₃ (get⁻¹-const b₁ b₂ p) ≡ get⁻¹-const b₁ b₃ p) Lens-as-Σ = Eq.↔→≃ (λ l → get l , get⁻¹-const l , get⁻¹-const-equivalence l , get⁻¹-const-∘ l) (λ (g , c , c-e , c-∘) → record { get = g ; get⁻¹-const = c ; get⁻¹-const-equivalence = c-e ; get⁻¹-const-∘ = c-∘ }) refl (λ { (lens _ _ _ _) → refl _ }) where open Lens -- A variant of Lens-as-Σ. Lens-as-Σ′ : Lens A B ≃ ∃ λ (get : A → B) → ∃ λ (get⁻¹-constant : (b₁ b₂ : B) → get ⁻¹ b₁ ≃ get ⁻¹ b₂) → let get⁻¹-const : ∀ _ _ → _ get⁻¹-const = λ b₁ b₂ → _≃_.to (get⁻¹-constant b₁ b₂) in (b₁ b₂ b₃ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₂ b₃ (get⁻¹-const b₁ b₂ p) ≡ get⁻¹-const b₁ b₃ p Lens-as-Σ′ {A = A} {B = B} = Lens A B ↝⟨ Lens-as-Σ ⟩ (∃ λ (get : A → B) → ∃ λ (get⁻¹-const : (b₁ b₂ : B) → get ⁻¹ b₁ → get ⁻¹ b₂) → ((b₁ b₂ : B) → Is-equivalence (get⁻¹-const b₁ b₂)) × ((b₁ b₂ b₃ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₂ b₃ (get⁻¹-const b₁ b₂ p) ≡ get⁻¹-const b₁ b₃ p)) ↔⟨ (∃-cong λ _ → Σ-assoc) ⟩ (∃ λ (get : A → B) → ∃ λ ((get⁻¹-const , _) : ∃ λ (get⁻¹-const : (b₁ b₂ : B) → get ⁻¹ b₁ → get ⁻¹ b₂) → (b₁ b₂ : B) → Is-equivalence (get⁻¹-const b₁ b₂)) → (b₁ b₂ b₃ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₂ b₃ (get⁻¹-const b₁ b₂ p) ≡ get⁻¹-const b₁ b₃ p) ↝⟨ (∃-cong λ _ → Σ-cong-contra (ΠΣ-comm F.∘ ∀-cong ext (λ _ → ΠΣ-comm)) λ _ → F.id) ⟩ (∃ λ (get : A → B) → ∃ λ (f : (b₁ b₂ : B) → ∃ λ (get⁻¹-const : get ⁻¹ b₁ → get ⁻¹ b₂) → Is-equivalence get⁻¹-const) → let get⁻¹-const : ∀ _ _ → _ get⁻¹-const = λ b₁ b₂ → proj₁ (f b₁ b₂) in (b₁ b₂ b₃ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₂ b₃ (get⁻¹-const b₁ b₂ p) ≡ get⁻¹-const b₁ b₃ p) ↝⟨ (∃-cong λ _ → Σ-cong-contra (∀-cong ext λ _ → ∀-cong ext λ _ → Eq.≃-as-Σ) λ _ → F.id) ⟩□ (∃ λ (get : A → B) → ∃ λ (get⁻¹-constant : (b₁ b₂ : B) → get ⁻¹ b₁ ≃ get ⁻¹ b₂) → let get⁻¹-const : ∀ _ _ → _ get⁻¹-const = λ b₁ b₂ → _≃_.to (get⁻¹-constant b₁ b₂) in (b₁ b₂ b₃ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₂ b₃ (get⁻¹-const b₁ b₂ p) ≡ get⁻¹-const b₁ b₃ p) □ ------------------------------------------------------------------------ -- Some results related to h-levels -- If the domain of a lens is inhabited and has h-level n, -- then the codomain also has h-level n. h-level-respects-lens-from-inhabited : ∀ n → Lens A B → A → H-level n A → H-level n B h-level-respects-lens-from-inhabited {A = A} {B = B} n l a = H-level n A ↝⟨ H-level.respects-surjection surj n ⟩□ H-level n B □ where open Lens l surj : A ↠ B surj = record { logical-equivalence = record { to = get ; from = set a } ; right-inverse-of = λ b → get (set a b) ≡⟨ get-set a b ⟩∎ b ∎ } -- If A and B have h-level n given the assumption that the other type -- is inhabited, then Lens A B has h-level n. lens-preserves-h-level : ∀ n → (B → H-level n A) → (A → H-level n B) → H-level n (Lens A B) lens-preserves-h-level {B = B} {A = A} n hA hB = H-level-cong _ n (inverse Lens-as-Σ′) $ Σ-closure n (Π-closure ext n λ a → hB a) λ _ → Σ-closure n (Π-closure ext n λ b → Π-closure ext n λ _ → Eq.h-level-closure ext n (⁻¹-closure (hA b) hB) (⁻¹-closure (hA b) hB)) λ _ → (Π-closure ext n λ b → Π-closure ext n λ _ → Π-closure ext n λ _ → Π-closure ext n λ _ → ⇒≡ n (⁻¹-closure (hA b) hB)) where ⁻¹-closure : {f : A → B} {x : B} → H-level n A → (A → H-level n B) → H-level n (f ⁻¹ x) ⁻¹-closure hA hB = Σ-closure n hA λ a → ⇒≡ n (hB a) -- If A has positive h-level n, then Lens A B also has h-level n. lens-preserves-h-level-of-domain : ∀ n → H-level (1 + n) A → H-level (1 + n) (Lens A B) lens-preserves-h-level-of-domain n hA = [inhabited⇒+]⇒+ n λ l → lens-preserves-h-level (1 + n) (λ _ → hA) λ a → h-level-respects-lens-from-inhabited _ l a hA ------------------------------------------------------------------------ -- Some equality characterisation lemmas -- An equality characterisation lemma. equality-characterisation : let open Lens in {A : Type a} {B : Type b} {l₁ l₂ : Lens A B} → (l₁ ≡ l₂) ≃ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (gc : ∀ b₁ b₂ p → subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) b₁ b₂ p ≡ get⁻¹-const l₂ b₁ b₂ p) → subst (λ (get , gc) → ∀ b₁ b₂ b₃ (p : get ⁻¹ b₁) → gc b₂ b₃ (gc b₁ b₂ p) ≡ gc b₁ b₃ p) (Σ-≡,≡→≡ (⟨ext⟩ g) (⟨ext⟩ λ b₁ → ⟨ext⟩ λ b₂ → ⟨ext⟩ λ p → gc b₁ b₂ p)) (get⁻¹-const-∘ l₁) ≡ get⁻¹-const-∘ l₂) equality-characterisation {l₁ = l₁} {l₂ = l₂} = l₁ ≡ l₂ ↝⟨ inverse $ Eq.≃-≡ (lemma₁ F.∘ Lens-as-Σ) ⟩ ( ((get l₁ , get⁻¹-const l₁) , get⁻¹-const-∘ l₁) , get⁻¹-const-equivalence l₁ ) ≡ ( ((get l₂ , get⁻¹-const l₂) , get⁻¹-const-∘ l₂) , get⁻¹-const-equivalence l₂ ) ↔⟨ inverse $ ignore-propositional-component (Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → Eq.propositional ext _) ⟩ ((get l₁ , get⁻¹-const l₁) , get⁻¹-const-∘ l₁) ≡ ((get l₂ , get⁻¹-const l₂) , get⁻¹-const-∘ l₂) ↔⟨ inverse B.Σ-≡,≡↔≡ ⟩ (∃ λ (p : (get l₁ , get⁻¹-const l₁) ≡ (get l₂ , get⁻¹-const l₂)) → subst (λ (get , gc) → ∀ b₁ b₂ b₃ (p : get ⁻¹ b₁) → gc b₂ b₃ (gc b₁ b₂ p) ≡ gc b₁ b₃ p) p (get⁻¹-const-∘ l₁) ≡ get⁻¹-const-∘ l₂) ↝⟨ (Σ-cong-contra B.Σ-≡,≡↔≡ λ _ → F.id) ⟩ (∃ λ (p : ∃ λ (g : get l₁ ≡ get l₂) → subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) g (get⁻¹-const l₁) ≡ get⁻¹-const l₂) → subst (λ (get , gc) → ∀ b₁ b₂ b₃ (p : get ⁻¹ b₁) → gc b₂ b₃ (gc b₁ b₂ p) ≡ gc b₁ b₃ p) (uncurry Σ-≡,≡→≡ p) (get⁻¹-const-∘ l₁) ≡ get⁻¹-const-∘ l₂) ↔⟨ inverse Σ-assoc ⟩ (∃ λ (g : get l₁ ≡ get l₂) → ∃ λ (gc : subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) g (get⁻¹-const l₁) ≡ get⁻¹-const l₂) → subst (λ (get , gc) → ∀ b₁ b₂ b₃ (p : get ⁻¹ b₁) → gc b₂ b₃ (gc b₁ b₂ p) ≡ gc b₁ b₃ p) (Σ-≡,≡→≡ g gc) (get⁻¹-const-∘ l₁) ≡ get⁻¹-const-∘ l₂) ↝⟨ (Σ-cong-contra (Eq.extensionality-isomorphism bad-ext) λ _ → F.id) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (gc : subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) ≡ get⁻¹-const l₂) → subst (λ (get , gc) → ∀ b₁ b₂ b₃ (p : get ⁻¹ b₁) → gc b₂ b₃ (gc b₁ b₂ p) ≡ gc b₁ b₃ p) (Σ-≡,≡→≡ (⟨ext⟩ g) gc) (get⁻¹-const-∘ l₁) ≡ get⁻¹-const-∘ l₂) ↝⟨ (∃-cong λ _ → Σ-cong-contra (inverse $ lemma₂ _) λ _ → F.id) ⟩□ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (gc : ∀ b₁ b₂ p → subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) b₁ b₂ p ≡ get⁻¹-const l₂ b₁ b₂ p) → subst (λ (get , gc) → ∀ b₁ b₂ b₃ (p : get ⁻¹ b₁) → gc b₂ b₃ (gc b₁ b₂ p) ≡ gc b₁ b₃ p) (Σ-≡,≡→≡ (⟨ext⟩ g) (⟨ext⟩ λ b₁ → ⟨ext⟩ λ b₂ → ⟨ext⟩ λ p → gc b₁ b₂ p)) (get⁻¹-const-∘ l₁) ≡ get⁻¹-const-∘ l₂) □ where open Lens lemma₁ : {P : A → Type ℓ} {Q R : (x : A) → P x → Type ℓ} → (∃ λ (x : A) → ∃ λ (y : P x) → Q x y × R x y) ≃ (∃ λ (((x , y) , _) : Σ (Σ A P) (uncurry R)) → Q x y) lemma₁ {A = A} {P = P} {Q = Q} {R = R} = (∃ λ (x : A) → ∃ λ (y : P x) → Q x y × R x y) ↔⟨ (∃-cong λ _ → ∃-cong λ _ → ×-comm) ⟩ (∃ λ (x : A) → ∃ λ (y : P x) → R x y × Q x y) ↔⟨ (∃-cong λ _ → Σ-assoc) ⟩ (∃ λ (x : A) → ∃ λ ((y , _) : ∃ λ (y : P x) → R x y) → Q x y) ↔⟨ Σ-assoc ⟩ (∃ λ ((x , y , _) : ∃ λ (x : A) → ∃ λ (y : P x) → R x y) → Q x y) ↝⟨ (Σ-cong Σ-assoc λ _ → F.id) ⟩□ (∃ λ (((x , y) , _) : Σ (Σ A P) (uncurry R)) → Q x y) □ lemma₂ : (g : ∀ a → get l₁ a ≡ get l₂ a) → _ lemma₂ g = subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) ≡ get⁻¹-const l₂ ↝⟨ inverse $ Eq.extensionality-isomorphism bad-ext ⟩ (∀ b₁ → subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) b₁ ≡ get⁻¹-const l₂ b₁) ↝⟨ (∀-cong ext λ _ → inverse $ Eq.extensionality-isomorphism bad-ext) ⟩ (∀ b₁ b₂ → subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) b₁ b₂ ≡ get⁻¹-const l₂ b₁ b₂) ↝⟨ (∀-cong ext λ _ → ∀-cong ext λ _ → inverse $ Eq.extensionality-isomorphism bad-ext) ⟩□ (∀ b₁ b₂ p → subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) b₁ b₂ p ≡ get⁻¹-const l₂ b₁ b₂ p) □ -- An equality characterisation lemma for lenses from sets. equality-characterisation-for-sets : let open Lens in {A : Type a} {B : Type b} {l₁ l₂ : Lens A B} → Is-set A → (l₁ ≡ l₂) ≃ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∀ b₁ b₂ p → proj₁ (get⁻¹-const l₁ b₁ b₂ (subst (_⁻¹ b₁) (sym $ ⟨ext⟩ g) p)) ≡ proj₁ (get⁻¹-const l₂ b₁ b₂ p)) equality-characterisation-for-sets {A = A} {B = B} {l₁ = l₁} {l₂ = l₂} A-set = l₁ ≡ l₂ ↝⟨ equality-characterisation ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (gc : ∀ b₁ b₂ p → subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) b₁ b₂ p ≡ get⁻¹-const l₂ b₁ b₂ p) → subst (λ (get , gc) → ∀ b₁ b₂ b₃ (p : get ⁻¹ b₁) → gc b₂ b₃ (gc b₁ b₂ p) ≡ gc b₁ b₃ p) (Σ-≡,≡→≡ (⟨ext⟩ g) (⟨ext⟩ λ b₁ → ⟨ext⟩ λ b₂ → ⟨ext⟩ λ p → gc b₁ b₂ p)) (get⁻¹-const-∘ l₁) ≡ get⁻¹-const-∘ l₂) ↔⟨ (∃-cong λ _ → drop-⊤-right λ _ → _⇔_.to contractible⇔↔⊤ $ +⇒≡ $ Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → ⁻¹-set) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∀ b₁ b₂ p → subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) b₁ b₂ p ≡ get⁻¹-const l₂ b₁ b₂ p) ↝⟨ (∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ≡⇒↝ _ $ cong (_≡ _) $ lemma₁ _ _ _ _) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∀ b₁ b₂ p → subst (_⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁ b₁ b₂ (subst (_⁻¹ b₁) (sym $ ⟨ext⟩ g) p)) ≡ get⁻¹-const l₂ b₁ b₂ p) ↔⟨ (∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ∀-cong ext λ p → drop-⊤-right (λ _ → _⇔_.to contractible⇔↔⊤ $ +⇒≡ (B-set (proj₁ p))) F.∘ inverse B.Σ-≡,≡↔≡) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∀ b₁ b₂ p → proj₁ (subst (_⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁ b₁ b₂ (subst (_⁻¹ b₁) (sym $ ⟨ext⟩ g) p))) ≡ proj₁ (get⁻¹-const l₂ b₁ b₂ p)) ↝⟨ (∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ≡⇒↝ _ $ cong (_≡ _) $ lemma₂ _ _ _ _) ⟩□ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∀ b₁ b₂ p → proj₁ (get⁻¹-const l₁ b₁ b₂ (subst (_⁻¹ b₁) (sym $ ⟨ext⟩ g) p)) ≡ proj₁ (get⁻¹-const l₂ b₁ b₂ p)) □ where open Lens B-set : A → Is-set B B-set a = h-level-respects-lens-from-inhabited 2 l₁ a A-set ⁻¹-set : Is-set (get l₂ ⁻¹ b) ⁻¹-set = Σ-closure 2 A-set λ a → mono₁ 1 (B-set a) lemma₁ : ∀ g b₁ b₂ p → _ lemma₁ g b₁ b₂ p = subst (λ get → ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁) b₁ b₂ p ≡⟨ cong (λ f → f b₂ p) $ sym $ push-subst-application (⟨ext⟩ g) (λ get b₁ → ∀ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) ⟩ subst (λ get → ∀ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁ b₁) b₂ p ≡⟨ cong (λ f → f p) $ sym $ push-subst-application (⟨ext⟩ g) (λ get b₂ → get ⁻¹ b₁ → get ⁻¹ b₂) ⟩ subst (λ get → get ⁻¹ b₁ → get ⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁ b₁ b₂) p ≡⟨ subst-→ {x₁≡x₂ = ⟨ext⟩ g} ⟩∎ subst (_⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁ b₁ b₂ (subst (_⁻¹ b₁) (sym $ ⟨ext⟩ g) p)) ∎ lemma₂ : ∀ g b₁ b₂ p → _ lemma₂ g b₁ b₂ p = proj₁ (subst (_⁻¹ b₂) (⟨ext⟩ g) (get⁻¹-const l₁ b₁ b₂ (subst (_⁻¹ b₁) (sym $ ⟨ext⟩ g) p))) ≡⟨ cong proj₁ $ push-subst-pair {y≡z = ⟨ext⟩ g} _ _ ⟩ subst (λ _ → A) (⟨ext⟩ g) (proj₁ (get⁻¹-const l₁ b₁ b₂ (subst (_⁻¹ b₁) (sym $ ⟨ext⟩ g) p))) ≡⟨ subst-const (⟨ext⟩ g) ⟩∎ proj₁ (get⁻¹-const l₁ b₁ b₂ (subst (_⁻¹ b₁) (sym $ ⟨ext⟩ g) p)) ∎ ------------------------------------------------------------------------ -- Conversions between different kinds of lenses -- Higher lenses can be converted to the ones defined above. higher→ : Higher.Lens A B → Lens A B higher→ l@(Higher.⟨ _ , _ , _ ⟩) = _≃_.from Lens-as-Σ′ ( Higher.Lens.get l , Higher.get⁻¹-constant l , Higher.get⁻¹-const-∘ l ) -- The conversion preserves getters and setters. higher→-preserves-getters-and-setters : Preserves-getters-and-setters-→ A B higher→ higher→-preserves-getters-and-setters Higher.⟨ _ , _ , _ ⟩ = refl _ , refl _ -- A lens of the kind defined above can be converted to a higher one -- if the codomain is inhabited when it is merely inhabited. →higher : (∥ B ∥ → B) → Lens A B → Higher.Lens A B →higher {B = B} {A = A} ∥B∥→B l@(lens _ _ _ _) = record { R = ∃ λ (b : ∥ B ∥) → get l ⁻¹ (∥B∥→B b) ; equiv = A ↔⟨ (inverse $ drop-⊤-right λ _ → _⇔_.to contractible⇔↔⊤ $ other-singleton-contractible _) ⟩ (∃ λ a → ∃ λ b → get l a ≡ b) ↔⟨ ∃-comm ⟩ (∃ λ b → get l ⁻¹ b) ↝⟨ (Σ-cong (inverse PT.∥∥×≃) λ _ → get⁻¹-constant l _ _) ⟩ (∃ λ ((b , _) : ∥ B ∥ × B) → get l ⁻¹ (∥B∥→B b)) ↔⟨ Σ-assoc F.∘ (∃-cong λ _ → ×-comm) F.∘ inverse Σ-assoc ⟩□ (∃ λ (b : ∥ B ∥) → get l ⁻¹ (∥B∥→B b)) × B □ ; inhabited = proj₁ } where open Lens -- The conversion preserves getters and setters. →higher-preserves-getters-and-setters : {B : Type b} (∥B∥→B : ∥ B ∥ → B) → Preserves-getters-and-setters-→ A B (→higher ∥B∥→B) →higher-preserves-getters-and-setters {A = A} ∥B∥→B l@(lens _ _ _ _) = refl _ , ⟨ext⟩ λ a → ⟨ext⟩ λ b → let a′ = set a b in _≃_.to-from (Higher.Lens.equiv (→higher ∥B∥→B l)) $ cong₂ _,_ (∣ get a′ ∣ , get⁻¹-const (get a′) (∥B∥→B ∣ get a′ ∣) (a′ , refl _) ≡⟨ Σ-≡,≡→≡ (PT.truncation-is-proposition _ _) ( subst (λ b → get ⁻¹ ∥B∥→B b) (PT.truncation-is-proposition _ _) (get⁻¹-const (get a′) (∥B∥→B ∣ get a′ ∣) (a′ , refl _)) ≡⟨ elim¹ (λ {f} _ → subst (λ b → get ⁻¹ f b) (PT.truncation-is-proposition _ _) (get⁻¹-const (get a′) (f ∣ get a′ ∣) (a′ , refl _)) ≡ get⁻¹-const (get a) (f ∣ get a ∣) (a , refl _)) ( subst (λ _ → get ⁻¹ ∥B∥→B ∣ b ∣) (PT.truncation-is-proposition _ _) (get⁻¹-const (get a′) (∥B∥→B ∣ b ∣) (a′ , refl _)) ≡⟨ subst-const (PT.truncation-is-proposition _ _) ⟩ get⁻¹-const (get a′) (∥B∥→B ∣ b ∣) (a′ , refl _) ≡⟨ sym $ get⁻¹-const-∘ _ _ _ _ ⟩ get⁻¹-const (get a) (∥B∥→B ∣ b ∣) (get⁻¹-const (get a′) (get a) (a′ , refl _)) ≡⟨ cong (get⁻¹-const (get a) (∥B∥→B ∣ b ∣)) $ elim¹ (λ {b} eq → get⁻¹-const (get a′) (get a) (a′ , refl _) ≡ get⁻¹-const b (get a) (a′ , eq)) (refl _) (get-set a b) ⟩ get⁻¹-const (get a) (∥B∥→B ∣ b ∣) (get⁻¹-const b (get a) (set a b , get-set a b)) ≡⟨⟩ get⁻¹-const (get a) (∥B∥→B ∣ b ∣) (get⁻¹-const b (get a) (get⁻¹-const (get a) b (a , refl _))) ≡⟨ cong (λ p → get⁻¹-const (get a) (∥B∥→B ∣ b ∣) (get⁻¹-const b (get a) p)) $ get⁻¹-const-inverse _ _ _ ⟩ get⁻¹-const (get a) (∥B∥→B ∣ b ∣) (get⁻¹-const b (get a) (get⁻¹-const⁻¹ b (get a) (a , refl _))) ≡⟨ cong (get⁻¹-const (get a) (∥B∥→B ∣ b ∣)) $ _≃_.right-inverse-of (get⁻¹-constant _ _) _ ⟩∎ get⁻¹-const (get a) (∥B∥→B ∣ b ∣) (a , refl _) ∎) (⟨ext⟩ λ _ → cong ∥B∥→B $ PT.truncation-is-proposition _ _) ⟩∎ get⁻¹-const (get a) (∥B∥→B ∣ get a ∣) (a , refl _) ∎) ⟩∎ ∣ get a ∣ , get⁻¹-const (get a) (∥B∥→B ∣ get a ∣) (a , refl _) ∎) (get (set a b) ≡⟨ get-set a b ⟩∎ b ∎) where open Lens l -- There is a split surjection from Lens A B to Higher.Lens A B if B -- is inhabited when it is merely inhabited (assuming univalence). ↠higher : {A : Type a} {B : Type b} → Univalence (a ⊔ b) → (∥ B ∥ → B) → Lens A B ↠ Higher.Lens A B ↠higher {A = A} {B = B} univ ∥B∥→B = record { logical-equivalence = record { to = →higher ∥B∥→B ; from = higher→ } ; right-inverse-of = λ l → Higher.lenses-equal-if-setters-equal univ _ _ (λ _ → ∥B∥→B) (set (→higher ∥B∥→B (higher→ l)) ≡⟨ proj₂ $ →higher-preserves-getters-and-setters ∥B∥→B (higher→ l) ⟩ Lens.set (higher→ l) ≡⟨ proj₂ $ higher→-preserves-getters-and-setters l ⟩∎ set l ∎) } where open Higher.Lens -- The split surjection preserves getters and setters. ↠higher-preserves-getters-and-setters : {A : Type a} {B : Type b} (univ : Univalence (a ⊔ b)) (∥B∥→B : ∥ B ∥ → B) → Preserves-getters-and-setters-⇔ A B (_↠_.logical-equivalence (↠higher univ ∥B∥→B)) ↠higher-preserves-getters-and-setters _ ∥B∥→B = →higher-preserves-getters-and-setters ∥B∥→B , higher→-preserves-getters-and-setters -- If B is inhabited when it is merely inhabited and A has positive -- h-level n, then Higher.Lens A B also has h-level n (assuming -- univalence). higher-lens-preserves-h-level-of-domain : {A : Type a} {B : Type b} → Univalence (a ⊔ b) → (∥ B ∥ → B) → ∀ n → H-level (1 + n) A → H-level (1 + n) (Higher.Lens A B) higher-lens-preserves-h-level-of-domain {A = A} {B = B} univ ∥B∥→B n = H-level (1 + n) A ↝⟨ lens-preserves-h-level-of-domain n ⟩ H-level (1 + n) (Lens A B) ↝⟨ H-level.respects-surjection (↠higher univ ∥B∥→B) (1 + n) ⟩□ H-level (1 + n) (Higher.Lens A B) □ -- Traditional lenses that satisfy some coherence properties can be -- translated to lenses of the kind defined above. coherent→ : Block ""conversion"" → Traditional.Coherent-lens A B → Lens A B coherent→ ⊠ l = _≃_.from Lens-as-Σ′ ( get , (λ b₁ b₂ → Eq.↔→≃ (gg b₁ b₂) (gg b₂ b₁) (gg∘gg b₁ b₂) (gg∘gg b₂ b₁)) , (λ b₁ b₂ b₃ (a , _) → Σ-≡,≡→≡ (set (set a b₂) b₃ ≡⟨ set-set a b₂ b₃ ⟩∎ set a b₃ ∎) (subst (λ a → get a ≡ b₃) (set-set a b₂ b₃) (get-set (set a b₂) b₃) ≡⟨ subst-∘ _ _ (set-set a b₂ b₃) ⟩ subst (_≡ b₃) (cong get (set-set a b₂ b₃)) (get-set (set a b₂) b₃) ≡⟨ subst-trans-sym {y≡x = cong get (set-set a b₂ b₃)} ⟩ trans (sym (cong get (set-set a b₂ b₃))) (get-set (set a b₂) b₃) ≡⟨ get-set-set′ _ _ _ ⟩∎ get-set a b₃ ∎)) ) where open Traditional.Coherent-lens l get-set-set′ : ∀ a b₁ b₂ → trans (sym (cong get (set-set a b₁ b₂))) (get-set (set a b₁) b₂) ≡ get-set a b₂ get-set-set′ a b₁ b₂ = trans (sym (cong get (set-set a b₁ b₂))) (get-set (set a b₁) b₂) ≡⟨ cong (λ eq → trans (sym eq) (get-set _ _)) $ get-set-set _ _ _ ⟩ trans (sym (trans (get-set (set a b₁) b₂) (sym (get-set a b₂)))) (get-set (set a b₁) b₂) ≡⟨ cong (flip trans (get-set _ _)) $ sym-trans _ (sym (get-set _ _)) ⟩ trans (trans (sym (sym (get-set a b₂))) (sym (get-set (set a b₁) b₂))) (get-set (set a b₁) b₂) ≡⟨ trans-[trans-sym]- _ (get-set _ _) ⟩ sym (sym (get-set a b₂)) ≡⟨ sym-sym (get-set _ _) ⟩∎ get-set a b₂ ∎ gg : ∀ b₁ b₂ → get ⁻¹ b₁ → get ⁻¹ b₂ gg b₁ b₂ (a , _) = set a b₂ , get-set a b₂ gg∘gg : ∀ b₁ b₂ p → gg b₁ b₂ (gg b₂ b₁ p) ≡ p gg∘gg b₁ b₂ (a , get-a≡b₂) = Σ-≡,≡→≡ eq₁ (subst (λ a → get a ≡ b₂) eq₁ (get-set (set a b₁) b₂) ≡⟨ subst-∘ _ _ eq₁ ⟩ subst (_≡ b₂) (cong get eq₁) (get-set (set a b₁) b₂) ≡⟨ subst-trans-sym {y≡x = cong get eq₁} ⟩ trans (sym (cong get eq₁)) (get-set (set a b₁) b₂) ≡⟨ cong (flip trans (get-set (set a b₁) b₂)) lemma₂ ⟩ trans (trans (trans (sym (cong get (set-get a))) (cong (get ⊚ set a) get-a≡b₂)) (sym (cong get (set-set a b₁ b₂)))) (get-set (set a b₁) b₂) ≡⟨ trans-assoc _ _ (get-set (set a b₁) b₂) ⟩ trans (trans (sym (cong get (set-get a))) (cong (get ⊚ set a) get-a≡b₂)) (trans (sym (cong get (set-set a b₁ b₂))) (get-set (set a b₁) b₂)) ≡⟨ trans-assoc _ _ (trans (sym (cong get (set-set a b₁ b₂))) (get-set (set a b₁) b₂)) ⟩ trans (sym (cong get (set-get a))) (trans (cong (get ⊚ set a) get-a≡b₂) (trans (sym (cong get (set-set a b₁ b₂))) (get-set (set a b₁) b₂))) ≡⟨ cong₂ (λ p q → trans (sym p) (trans (cong (get ⊚ set a) get-a≡b₂) q)) (get-set-get _) (get-set-set′ _ _ _) ⟩ trans (sym (get-set a (get a))) (trans (cong (get ⊚ set a) get-a≡b₂) (get-set a b₂)) ≡⟨ cong (λ eq → trans (sym (eq (get a))) (trans (cong (get ⊚ set a) get-a≡b₂) (eq b₂))) $ sym $ _≃_.left-inverse-of (Eq.extensionality-isomorphism bad-ext) _ ⟩ trans (sym (ext⁻¹ (⟨ext⟩ (get-set a)) (get a))) (trans (cong (get ⊚ set a) get-a≡b₂) (ext⁻¹ (⟨ext⟩ (get-set a)) b₂)) ≡⟨ elim₁ (λ {f} gs → trans (sym (ext⁻¹ gs (get a))) (trans (cong f get-a≡b₂) (ext⁻¹ gs b₂)) ≡ get-a≡b₂) ( trans (sym (ext⁻¹ (refl id) (get a))) (trans (cong id get-a≡b₂) (ext⁻¹ (refl id) b₂)) ≡⟨ cong₂ (λ p q → trans (sym p) (trans (cong id get-a≡b₂) q)) (ext⁻¹-refl _) (ext⁻¹-refl _) ⟩ trans (sym (refl _)) (trans (cong id get-a≡b₂) (refl _)) ≡⟨ cong₂ trans sym-refl (trans-reflʳ _) ⟩ trans (refl _) (cong id get-a≡b₂) ≡⟨ trans-reflˡ (cong id get-a≡b₂) ⟩ cong id get-a≡b₂ ≡⟨ sym $ cong-id get-a≡b₂ ⟩∎ get-a≡b₂ ∎) (⟨ext⟩ (get-set a)) ⟩ get-a≡b₂ ∎) where eq₁ = set (set a b₁) b₂ ≡⟨ set-set a b₁ b₂ ⟩ set a b₂ ≡⟨ cong (set a) (sym get-a≡b₂) ⟩ set a (get a) ≡⟨ set-get a ⟩∎ a ∎ lemma₁ = sym (cong get (cong (set a) (sym get-a≡b₂))) ≡⟨ cong sym $ cong-∘ _ _ (sym get-a≡b₂) ⟩ sym (cong (get ⊚ set a) (sym get-a≡b₂)) ≡⟨ sym $ cong-sym _ (sym get-a≡b₂) ⟩ cong (get ⊚ set a) (sym (sym get-a≡b₂)) ≡⟨ cong (cong (get ⊚ set a)) $ sym-sym get-a≡b₂ ⟩∎ cong (get ⊚ set a) get-a≡b₂ ∎ lemma₂ = sym (cong get eq₁) ≡⟨⟩ sym (cong get (trans (set-set a b₁ b₂) (trans (cong (set a) (sym get-a≡b₂)) (set-get a)))) ≡⟨ cong sym $ cong-trans _ _ (trans (cong (set a) (sym get-a≡b₂)) (set-get a)) ⟩ sym (trans (cong get (set-set a b₁ b₂)) (cong get (trans (cong (set a) (sym get-a≡b₂)) (set-get a)))) ≡⟨ cong (λ eq → sym (trans _ eq)) $ cong-trans _ _ (set-get a) ⟩ sym (trans (cong get (set-set a b₁ b₂)) (trans (cong get (cong (set a) (sym get-a≡b₂))) (cong get (set-get a)))) ≡⟨ sym-trans _ (trans (cong get (cong (set a) (sym get-a≡b₂))) (cong get (set-get a))) ⟩ trans (sym (trans (cong get (cong (set a) (sym get-a≡b₂))) (cong get (set-get a)))) (sym (cong get (set-set a b₁ b₂))) ≡⟨ cong (flip trans (sym (cong get (set-set a b₁ b₂)))) $ sym-trans _ (cong get (set-get a)) ⟩ trans (trans (sym (cong get (set-get a))) (sym (cong get (cong (set a) (sym get-a≡b₂))))) (sym (cong get (set-set a b₁ b₂))) ≡⟨ cong (λ eq → trans (trans (sym (cong get (set-get a))) eq) (sym (cong get (set-set a b₁ b₂)))) lemma₁ ⟩∎ trans (trans (sym (cong get (set-get a))) (cong (get ⊚ set a) get-a≡b₂)) (sym (cong get (set-set a b₁ b₂))) ∎ -- The conversion preserves getters and setters. coherent→-preserves-getters-and-setters : (b : Block ""conversion"") → Preserves-getters-and-setters-→ A B (coherent→ b) coherent→-preserves-getters-and-setters ⊠ _ = refl _ , refl _ -- If A is a set, then Traditional.Lens A B is equivalent to Lens A B. traditional≃ : Block ""conversion"" → Is-set A → Traditional.Lens A B ≃ Lens A B traditional≃ {A = A} {B = B} b@⊠ A-set = Eq.↔→≃ (Traditional.Lens A B ↔⟨ Traditional.≃coherent A-set ⟩ Traditional.Coherent-lens A B ↝⟨ coherent→ b ⟩□ Lens A B □) Lens.traditional-lens (λ l → _≃_.from (equality-characterisation-for-sets A-set) ( (λ _ → refl _) , (λ b₁ b₂ p@(a , _) → let l′ = traditional-lens l l″ = coherent→ b (_≃_.to (Traditional.≃coherent A-set) l′) in proj₁ (get⁻¹-const l″ b₁ b₂ (subst (_⁻¹ b₁) (sym $ ⟨ext⟩ λ _ → refl _) p)) ≡⟨ cong (λ eq → proj₁ (get⁻¹-const l″ b₁ b₂ (subst (_⁻¹ b₁) (sym eq) p))) ext-refl ⟩ proj₁ (get⁻¹-const l″ b₁ b₂ (subst (_⁻¹ b₁) (sym (refl _)) p)) ≡⟨ cong (λ eq → proj₁ (get⁻¹-const l″ b₁ b₂ (subst (_⁻¹ b₁) eq p))) sym-refl ⟩ proj₁ (get⁻¹-const l″ b₁ b₂ (subst (_⁻¹ b₁) (refl _) p)) ≡⟨ cong (proj₁ ⊚ get⁻¹-const l″ b₁ b₂) $ subst-refl _ _ ⟩ proj₁ (get⁻¹-const l″ b₁ b₂ p) ≡⟨⟩ set l (proj₁ p) b₂ ≡⟨⟩ proj₁ (get⁻¹-const l (get l a) b₂ (a , refl _)) ≡⟨ elim¹ (λ {b} eq → proj₁ (get⁻¹-const l (get l a) b₂ (a , refl _)) ≡ proj₁ (get⁻¹-const l b b₂ (a , eq))) (refl _) (proj₂ p) ⟩∎ proj₁ (get⁻¹-const l b₁ b₂ p) ∎) )) (λ _ → _↔_.from (Traditional.equality-characterisation-for-sets A-set) (refl _)) where open Lens B-set : Traditional.Lens A B → A → Is-set B B-set l a = Traditional.h-level-respects-lens-from-inhabited 2 l a A-set -- The equivalence preserves getters and setters. traditional≃-preserves-getters-and-setters : {A : Type a} (b : Block ""conversion"") (s : Is-set A) → Preserves-getters-and-setters-⇔ A B (_≃_.logical-equivalence (traditional≃ b s)) traditional≃-preserves-getters-and-setters ⊠ _ = (λ _ → refl _ , refl _) , (λ _ → refl _ , refl _) -- If B is inhabited when it is merely inhabited, then -- Traditional.Coherent-lens A B is logically equivalent to -- Higher.Lens A B. coherent⇔higher : Block ""conversion"" → (∥ B ∥ → B) → Traditional.Coherent-lens A B ⇔ Higher.Lens A B coherent⇔higher {B = B} {A = A} b ∥B∥→B = record { to = Traditional.Coherent-lens A B ↝⟨ coherent→ b ⟩ Lens A B ↝⟨ →higher ∥B∥→B ⟩□ Higher.Lens A B □ ; from = Higher.Lens.coherent-lens } -- The logical equivalence preserves getters and setters. coherent⇔higher-preserves-getters-and-setters : {B : Type b} (bc : Block ""conversion"") (∥B∥→B : ∥ B ∥ → B) → Preserves-getters-and-setters-⇔ A B (coherent⇔higher bc ∥B∥→B) coherent⇔higher-preserves-getters-and-setters b ∥B∥→B = Preserves-getters-and-setters-→-∘ {f = →higher ∥B∥→B} {g = coherent→ b} (→higher-preserves-getters-and-setters ∥B∥→B) (coherent→-preserves-getters-and-setters b) , (λ _ → refl _ , refl _) -- If B is inhabited when it is merely inhabited, then there is a -- split surjection from Traditional.Coherent-lens A B to -- Higher.Lens A B (assuming univalence). coherent↠higher : {A : Type a} {B : Type b} → Block ""conversion"" → Univalence (a ⊔ b) → (∥ B ∥ → B) → Traditional.Coherent-lens A B ↠ Higher.Lens A B coherent↠higher {A = A} {B = B} b univ ∥B∥→B = record { logical-equivalence = coherent⇔higher b ∥B∥→B ; right-inverse-of = λ l → Higher.lenses-equal-if-setters-equal univ _ _ (λ _ → ∥B∥→B) $ proj₂ (proj₁ (coherent⇔higher-preserves-getters-and-setters b ∥B∥→B) _) } -- The split surjection preserves getters and setters. coherent↠higher-preserves-getters-and-setters : {A : Type a} {B : Type b} (bc : Block ""conversion"") (univ : Univalence (a ⊔ b)) (∥B∥→B : ∥ B ∥ → B) → Preserves-getters-and-setters-⇔ A B (_↠_.logical-equivalence (coherent↠higher bc univ ∥B∥→B)) coherent↠higher-preserves-getters-and-setters b _ ∥B∥→B = coherent⇔higher-preserves-getters-and-setters b ∥B∥→B ------------------------------------------------------------------------ -- Composition -- A lemma used to define composition. ∘⁻¹≃ : Block ""∘⁻¹≃"" → (f : B → C) (g : A → B) → f ⊚ g ⁻¹ z ≃ ∃ λ ((y , _) : f ⁻¹ z) → g ⁻¹ y ∘⁻¹≃ ⊠ = F.∘⁻¹≃ -- Composition. infixr 9 _∘_ _∘_ : Lens B C → Lens A B → Lens A C l₁@(lens _ _ _ _) ∘ l₂@(lens _ _ _ _) = block λ b → _≃_.from Lens-as-Σ′ ( get l₁ ⊚ get l₂ , (λ c₁ c₂ → get l₁ ⊚ get l₂ ⁻¹ c₁ ↝⟨ ∘⁻¹≃ b _ _ ⟩ (∃ λ ((b , _) : get l₁ ⁻¹ c₁) → get l₂ ⁻¹ b) ↝⟨ (Σ-cong (get⁻¹-constant l₁ c₁ c₂) λ p@(b , _) → get⁻¹-constant l₂ b (proj₁ (get⁻¹-const l₁ c₁ c₂ p))) ⟩ (∃ λ ((b , _) : get l₁ ⁻¹ c₂) → get l₂ ⁻¹ b) ↝⟨ inverse $ ∘⁻¹≃ b _ _ ⟩□ get l₁ ⊚ get l₂ ⁻¹ c₂ □) , (λ c₁ c₂ c₃ p → _≃_.from (∘⁻¹≃ b _ _) (Σ-map (get⁻¹-const l₁ c₂ c₃) (λ {p@(b , _)} → get⁻¹-const l₂ b (proj₁ (get⁻¹-const l₁ c₂ c₃ p))) (_≃_.to (∘⁻¹≃ b _ _) (_≃_.from (∘⁻¹≃ b _ _) (Σ-map (get⁻¹-const l₁ c₁ c₂) (λ {p@(b , _)} → get⁻¹-const l₂ b (proj₁ (get⁻¹-const l₁ c₁ c₂ p))) (_≃_.to (∘⁻¹≃ b _ _) p))))) ≡⟨ cong (λ x → _≃_.from (∘⁻¹≃ b _ _) (Σ-map (get⁻¹-const l₁ c₂ c₃) (λ {p@(b , _)} → get⁻¹-const l₂ b (proj₁ (get⁻¹-const l₁ c₂ c₃ p))) x)) $ _≃_.right-inverse-of (∘⁻¹≃ b _ _) _ ⟩ _≃_.from (∘⁻¹≃ b _ _) (Σ-map (get⁻¹-const l₁ c₂ c₃) (λ {p@(b , _)} → get⁻¹-const l₂ b (proj₁ (get⁻¹-const l₁ c₂ c₃ p))) (Σ-map (get⁻¹-const l₁ c₁ c₂) (λ {p@(b , _)} → get⁻¹-const l₂ b (proj₁ (get⁻¹-const l₁ c₁ c₂ p))) (_≃_.to (∘⁻¹≃ b _ _) p))) ≡⟨⟩ _≃_.from (∘⁻¹≃ b _ _) (Σ-map (get⁻¹-const l₁ c₂ c₃ ⊚ get⁻¹-const l₁ c₁ c₂) (λ {p@(b , _)} → get⁻¹-const l₂ (proj₁ (get⁻¹-const l₁ c₁ c₂ p)) (proj₁ (get⁻¹-const l₁ c₂ c₃ (get⁻¹-const l₁ c₁ c₂ p))) ⊚ get⁻¹-const l₂ b (proj₁ (get⁻¹-const l₁ c₁ c₂ p))) (_≃_.to (∘⁻¹≃ b _ _) p)) ≡⟨ cong (λ f → _≃_.from (∘⁻¹≃ b _ _) (Σ-map (get⁻¹-const l₁ c₂ c₃ ⊚ get⁻¹-const l₁ c₁ c₂) (λ {p} → f {p}) (_≃_.to (∘⁻¹≃ b _ _) p))) $ (implicit-extensionality ext λ p → ⟨ext⟩ (get⁻¹-const-∘ l₂ _ (proj₁ (get⁻¹-const l₁ c₁ c₂ p)) _)) ⟩ _≃_.from (∘⁻¹≃ b _ _) (Σ-map (get⁻¹-const l₁ c₂ c₃ ⊚ get⁻¹-const l₁ c₁ c₂) (λ {p@(b , _)} → get⁻¹-const l₂ b (proj₁ (get⁻¹-const l₁ c₂ c₃ (get⁻¹-const l₁ c₁ c₂ p)))) (_≃_.to (∘⁻¹≃ b _ _) p)) ≡⟨ cong (λ f → _≃_.from (∘⁻¹≃ b _ _) (Σ-map f (λ {p@(b , _)} → get⁻¹-const l₂ b (proj₁ (f p))) (_≃_.to (∘⁻¹≃ b _ _) p))) $ ⟨ext⟩ (get⁻¹-const-∘ l₁ _ _ _) ⟩∎ _≃_.from (∘⁻¹≃ b _ _) (Σ-map (get⁻¹-const l₁ c₁ c₃) (λ {p@(b , _)} → get⁻¹-const l₂ b (proj₁ (get⁻¹-const l₁ c₁ c₃ p))) (_≃_.to (∘⁻¹≃ b _ _) p)) ∎) ) where open Lens -- The setter of the resulting lens is defined in the ""right"" way. set-∘≡ : (l₁ : Lens B C) (l₂ : Lens A B) → Lens.set (l₁ ∘ l₂) a c ≡ Lens.set l₂ a (Lens.set l₁ (Lens.get l₂ a) c) set-∘≡ (lens _ _ _ _) (lens _ _ _ _) = refl _ -- Composition for higher lenses, defined under the assumption that -- the resulting codomain is inhabited if it is merely inhabited. infix 9 ⟨_⟩_⊚_ ⟨_⟩_⊚_ : (∥ C ∥ → C) → Higher.Lens B C → Higher.Lens A B → Higher.Lens A C ⟨_⟩_⊚_ {C = C} {B = B} {A = A} ∥C∥→C = curry ( Higher.Lens B C × Higher.Lens A B ↝⟨ Σ-map higher→ higher→ ⟩ Lens B C × Lens A B ↝⟨ uncurry _∘_ ⟩ Lens A C ↝⟨ →higher ∥C∥→C ⟩□ Higher.Lens A C □) -- The setter of the resulting lens is defined in the ""right"" way. set-⊚≡ : ∀ ∥C∥→C (l₁ : Higher.Lens B C) (l₂ : Higher.Lens A B) → Higher.Lens.set (⟨ ∥C∥→C ⟩ l₁ ⊚ l₂) a c ≡ Higher.Lens.set l₂ a (Higher.Lens.set l₁ (Higher.Lens.get l₂ a) c) set-⊚≡ {a = a} {c = c} ∥C∥→C l₁ l₂ = set (⟨ ∥C∥→C ⟩ l₁ ⊚ l₂) a c ≡⟨ cong (λ f → f a c) $ proj₂ $ →higher-preserves-getters-and-setters ∥C∥→C (higher→ l₁ ∘ higher→ l₂) ⟩ Lens.set (higher→ l₁ ∘ higher→ l₂) a c ≡⟨ set-∘≡ (higher→ l₁) (higher→ l₂) ⟩ Lens.set (higher→ l₂) a (Lens.set (higher→ l₁) (Lens.get (higher→ l₂) a) c) ≡⟨ cong (λ f → Lens.set (higher→ l₂) a (Lens.set (higher→ l₁) (f a) c)) $ proj₁ $ higher→-preserves-getters-and-setters l₂ ⟩ Lens.set (higher→ l₂) a (Lens.set (higher→ l₁) (get l₂ a) c) ≡⟨ cong (λ f → Lens.set (higher→ l₂) a (f (get l₂ a) c)) $ proj₂ $ higher→-preserves-getters-and-setters l₁ ⟩ Lens.set (higher→ l₂) a (set l₁ (get l₂ a) c) ≡⟨ cong (λ f → f a (set l₁ (get l₂ a) c)) $ proj₂ $ higher→-preserves-getters-and-setters l₂ ⟩∎ set l₂ a (set l₁ (get l₂ a) c) ∎ where open Higher.Lens -- The implementation of composition for higher lenses given above -- matches the one in HC when both are defined (assuming univalence). ⊚≡∘ : ∀ a b {A : Type (a ⊔ b ⊔ c)} {B : Type (b ⊔ c)} {C : Type c} → Univalence (a ⊔ b ⊔ c) → (∥C∥→C : ∥ C ∥ → C) → ⟨_⟩_⊚_ {B = B} {A = A} ∥C∥→C ≡ HC.⟨ a , b ⟩_∘_ ⊚≡∘ a b {A = A} {B = B} {C = C} univ ∥C∥→C = HC.composition≡∘ a b univ ∥C∥→C ⟨ ∥C∥→C ⟩_⊚_ (λ l₁ l₂ _ _ → set-⊚≡ ∥C∥→C l₁ l₂) ",16314,True,3467.032065566052,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.layouts { import flash.geom.ColorTransform; import flash.geom.Point; import flash.geom.Vector3D; import mx.core.IVisualElement; import mx.core.UIComponent; import spark.layouts.HorizontalAlign; import spark.layouts.VerticalAlign; import spark.primitives.supportClasses.GraphicElement; import spark.layouts.supportClasses.PerspectiveAnimationNavigatorLayoutBase; // for asdoc [Experimental] /** * A CarouselLayout class arranges the layout elements in a * sequence along an arc, with one of them at a time selected. * *

The position of the elements is determined by the radii * radiusX, radiusY and radiusZ. * These can be properties can be set the negative values to produce * a ring of elements surrounding the view point.

* *

The rotation of the elements is determined by the * rotationX and rotationY properties.

*
    *
  • If a value of ""none"" is used for a rotation property, * no rotation is applied to the element around the corresponding axis.
  • * *
  • If a value of ""standard"" is used for a rotation property, * the element will be rotated so that it faces outwards around the arc.
  • * *
  • If a value of ""reversed"" is used for a rotation property, * the element will be rotated so that it faces inwards around the arc.
  • *
* * @mxml * *

The <st:CarouselLayout> tag inherits all of the * tag attributes of its superclass, and adds the following tag attributes:

* *
	 *  <st:AccordionLayout
	 *    Properties
	 *    angle=""360""
	 *    depthColor=""-1""
	 *    depthColorAlpha=""1""
	 *    horizontalAlign=""center|left|right""
	 *    horizontalAlignOffset=""0""
	 *    horizontalAlignOffsetPercent=""0""
	 *    numUnselectedElements=""-1""
	 *    radiusX=""100""
	 *    radiusY=""0""
	 *    radiusZ=""NaN""
	 *    rotateX=""none|reversed|standard""
	 *    rotateY=""none|reversed|standard""
	 *    verticalAlign=""bottom|middle|top""
	 *    verticalAlignOffset=""0""
	 *    verticalAlignOffsetPercent=""0""
	 *  />
	 *  
* * @includeExample examples/CarouselLayoutExample.mxml * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class CarouselLayout extends PerspectiveAnimationNavigatorLayoutBase { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function CarouselLayout() { super( INDIRECT ); _transformCalculator = new TransformValues( this ); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var _transformCalculator : TransformValues; /** * @private */ private var _horizontalCenterMultiplier : Number; /** * @private */ private var _verticalCenterMultiplier : Number; /** * @private */ private var _elementHorizontalCenterMultiplier : Number; /** * @private */ private var _elementVerticalCenterMultiplier : Number; /** * @private */ private var _displayedElements : Vector. //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // angle //---------------------------------- /** * @private * Storage property for angle. */ private var _angle:Number = 360; /** * The segment of a circle to rotate the elements around. * * @default 360 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get angle():Number { return _angle; } /** * @private */ public function set angle( value:Number ) : void { if( _angle == value ) return; _angle = value; invalidateTargetDisplayList(); } //---------------------------------- // rotateX //---------------------------------- /** * @private * Storage property for rotateX. */ private var _rotateX:int = 0; [Inspectable(category=""General"", enumeration=""none,reversed,standard"", defaultValue=""none"")] /** * Whether rotation should be applied to the x axis of elements. * * @default true * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get rotateX():String { return _rotateX ? _rotateX < 0 ? ""reversed"" : ""standard"" : ""none""; } /** * @private */ public function set rotateX( value:String ) : void { var r:int; switch( value ) { case ""reversed"" : { r = -1; break; } case ""standard"" : { r = 1; break; } default : { r = 0; } } if( _rotateX == r ) return; _rotateX = r; invalidateTargetDisplayList(); } //---------------------------------- // rotateY //---------------------------------- /** * @private * Storage property for rotateY. */ private var _rotateY:int = 1; [Inspectable(category=""General"", enumeration=""none,reversed,standard"", defaultValue=""standard"")] /** * Whether rotation should be applied to the y axis of elements. * * @default true * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get rotateY():String { return _rotateY ? _rotateY < 0 ? ""reversed"" : ""standard"" : ""none""; } /** * @private */ public function set rotateY( value:String ) : void { var r:int; switch( value ) { case ""reversed"" : { r = -1; break; } case ""standard"" : { r = 1; break; } default : { r = 0; } } if( r == _rotateY ) return; _rotateY = r; invalidateTargetDisplayList(); } //---------------------------------- // depthColor //---------------------------------- /** * @private * Storage property for depthColor. */ private var _depthColor : int = -1; [Inspectable(category=""General"", defaultValue=""-1"")] /** * The color tint to apply to elements as their are moved back on the z axis. * *

If a valid color is added to elements are tinted as they are moved * back on the z axis taking into account the depthColorAlpha * specified. If a value of -1 is set for the color no tinting is applied.

* * @default -1 * * @see #depthColorAlpha * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get depthColor():int { return _depthColor; } /** * @private */ public function set depthColor( value:int ) : void { if( _depthColor == value ) return; _depthColor = value; invalidateTargetDisplayList(); } //---------------------------------- // depthColorAlpha //---------------------------------- /** * @private * Storage property for depthColorAlpha. */ private var _depthColorAlpha : Number = 1; [Inspectable(category=""General"", defaultValue=""1"")] /** * The alpha to be used for the color tint that is applied to elements * as their are moved back on the z axis. * * @default 1 * * @see #depthColor * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get depthColorAlpha():Number { return _depthColorAlpha; } /** * @private */ public function set depthColorAlpha( value:Number ) : void { if( _depthColorAlpha == value ) return; _depthColorAlpha = value; invalidateTargetDisplayList(); } //---------------------------------- // numUnselectedElements //---------------------------------- /** * @private * Storage property for numUnselectedElements. */ private var _numUnselectedElements : int = -1; [Inspectable(category=""General"", defaultValue=""-1"")] /** * The number of items to show either side of the selected item * are positioned around this element. * *

Valid values are HorizontalAlign.LEFT, HorizontalAlign.CENTER * and HorizontalAlign.RIGHT.

* * @default 2 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get numUnselectedElements():int { return _numUnselectedElements; } /** * @private */ public function set numUnselectedElements( value:int ) : void { if( _numUnselectedElements == value ) return; _numUnselectedElements = value; invalidateTargetDisplayList(); } //---------------------------------- // horizontalAlign //---------------------------------- /** * @private * Storage property for horizontalAlign. */ private var _horizontalAlign:String = HorizontalAlign.CENTER; /** * @private * Flag to indicate the horizontalAlign property has changed. */ private var _horizontalAlignChange:Boolean = true; [Inspectable(category=""General"", enumeration=""left,right,center"", defaultValue=""center"")] /** * The horizontal position of the selected element in the viewport. All other elements * are positioned around this element. * *

Valid values are HorizontalAlign.LEFT, HorizontalAlign.CENTER * and HorizontalAlign.RIGHT.

* * @default ""center"" * * @see #horizontalAlignOffset * @see #horizontalAlignOffsetPercent * @see spark.layouts.HorizontalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get horizontalAlign():String { return _horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { if( value == _horizontalAlign ) return; _horizontalAlign = value; _horizontalAlignChange = true; invalidateTargetDisplayList(); } //---------------------------------- // verticalAlign //---------------------------------- /** * @private * Storage property for verticalAlign. */ private var _verticalAlign:String = VerticalAlign.MIDDLE; /** * @private * Flag to indicate the verticalAlign property has changed. */ private var _verticalAlignChange:Boolean = true; [Inspectable(category=""General"", enumeration=""top,bottom,middle"", defaultValue=""middle"")] /** * The vertical position of the selected element in the viewport. All other elements * are positioned around this element. * *

Valid values are VerticalAlign.TOP, VerticalAlign.MIDDLE * and VerticalAlign.BOTTOM.

* * @default ""middle"" * * @see #verticalAlignOffset * @see #verticalAlignOffsetPercent * @see spark.layouts.VerticalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get verticalAlign():String { return _verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if( value == _verticalAlign ) return; _verticalAlign = value; _verticalAlignChange = true; invalidateTargetDisplayList(); } //---------------------------------- // horizontalAlignOffset //---------------------------------- /** * @private * Storage property for horizontalAlignOffset. */ private var _horizontalAlignOffset:Number = 0; [Inspectable(category=""General"", defaultValue=""0"")] /** * The offset in pixels to be used in conjunction with horizontalAlign * to set the horizontal position of the selected element in the viewport. All other elements * are positioned around this element. * *

If horizontalAlignOffsetPercent is set after this property, * this property is set automatically depending on the value of horizontalAlignOffsetPercent.

* * @default 0 * * @see #horizontalAlign * @see #horizontalAlignOffsetPercent * @see spark.layouts.HorizontalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get horizontalAlignOffset():Number { return _horizontalAlignOffset; } /** * @private */ public function set horizontalAlignOffset(value:Number):void { if( _horizontalAlignOffset == value ) return; _horizontalAlignOffset = value; _horizontalAlignOffsetPercent = NaN; invalidateTargetDisplayList(); } //---------------------------------- // verticalAlignOffset //---------------------------------- /** * @private * Storage property for verticalAlignOffset. */ private var _verticalAlignOffset:Number = 0; [Inspectable(category=""General"", defaultValue=""0"")] /** * The offset in pixels to be used in conjunction with verticalAlign * to set the vertical position of the selected element in the viewport. All other elements * are positioned around this element. * *

If verticalAlignOffsetPercent is set after this property, * this property is set automatically depending on the value of verticalAlignOffsetPercent.

* * @default 0 * * @see #verticalAlign * @see #verticalAlignOffsetPercent * @see spark.layouts.VerticalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get verticalAlignOffset():Number { return _verticalAlignOffset; } /** * @private */ public function set verticalAlignOffset(value:Number):void { if( _verticalAlignOffset == value ) return; _verticalAlignOffset = value; _verticalAlignOffsetPercent = NaN; // _indicesInViewChanged = true; invalidateTargetDisplayList(); } //---------------------------------- // horizontalAlignOffsetPercent //---------------------------------- /** * @private * Storage property for horizontalAlignOffsetPercent. */ private var _horizontalAlignOffsetPercent:Number = 0; [Inspectable(category=""General"", defaultValue=""0"")] /** * The offset as a percentage of the unscaled width of the viewport * to be used in conjunction with horizontalAlign to set the horizontal * position of the selected element in the viewport. All other elements are * positioned around this element. * *

Setting this property overrides any value set on horizontalAlignOffset.

* * @default 0 * * @see #horizontalAlign * @see #horizontalAlignOffset * @see spark.layouts.HorizontalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get horizontalAlignOffsetPercent():Number { return _horizontalAlignOffsetPercent; } /** * @private */ public function set horizontalAlignOffsetPercent(value:Number):void { if( _horizontalAlignOffsetPercent == value ) return; _horizontalAlignOffsetPercent = value; if( !isNaN( _horizontalAlignOffsetPercent ) ) _horizontalAlignOffset = unscaledHeight * ( _horizontalAlignOffsetPercent / 100 ); // _indicesInViewChanged = true; invalidateTargetDisplayList(); } //---------------------------------- // verticalAlignOffsetPercent //---------------------------------- /** * @private * Storage property for verticalAlignOffsetPercent. */ private var _verticalAlignOffsetPercent:Number = 0; [Inspectable(category=""General"", defaultValue=""0"")] /** * The offset as a percentage of the unscaled height of the viewport * to be used in conjunction with verticalAlign to set the vertical * position of the selected element in the viewport. All other elements are * positioned around this element. * *

Setting this property overrides any value set on verticalAlignOffset.

* * @default 0 * * @see #verticalAlign * @see #verticalAlignOffset * @see spark.layouts.VerticalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get verticalAlignOffsetPercent():Number { return _verticalAlignOffsetPercent; } /** * @private */ public function set verticalAlignOffsetPercent(value:Number):void { if( _verticalAlignOffsetPercent == value ) return; _verticalAlignOffsetPercent = value; if( !isNaN( _verticalAlignOffsetPercent ) ) _verticalAlignOffset = unscaledHeight * ( _verticalAlignOffsetPercent / 100 ); // _indicesInViewChanged = true; invalidateTargetDisplayList(); } //---------------------------------- // elementHorizontalAlign //---------------------------------- /** * @private * Storage property for elementHorizontalAlign. */ private var _elementHorizontalAlign:String = HorizontalAlign.CENTER; /** * @private * Flag to indicate the elementHorizontalAlign property has changed. */ private var _elementHorizontalAlignChange : Boolean = true; [Inspectable(category=""General"", enumeration=""left,right,center"", defaultValue=""center"")] /** * The horizontal transform point of elements. * *

Valid values are HorizontalAlign.LEFT, HorizontalAlign.CENTER * and HorizontalAlign.RIGHT.

* * @default ""center"" * * @see spark.layouts.HorizontalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get elementHorizontalAlign():String { return _elementHorizontalAlign; } /** * @private */ public function set elementHorizontalAlign(value:String):void { if( value == _elementHorizontalAlign ) return; _elementHorizontalAlign = value; _elementHorizontalAlignChange = true; invalidateTargetDisplayList(); } //---------------------------------- // elementVerticalAlign //---------------------------------- /** * @private * Storage property for elementVerticalAlign. */ private var _elementVerticalAlign:String = VerticalAlign.MIDDLE; /** * @private * Flag to indicate the elementVerticalAlign property has changed. */ private var _elementVerticalAlignChange : Boolean = true; [Inspectable(category=""General"", enumeration=""top,bottom,middle"", defaultValue=""middle"")] /** * The vertical transform point of elements. * *

Valid values are VerticalAlign.TOP, VerticalAlign.MIDDLE * and VerticalAlign.BOTTOM.

* * @default ""middle"" * * @see spark.layouts.VerticalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get elementVerticalAlign():String { return _elementVerticalAlign; } /** * @private */ public function set elementVerticalAlign(value:String):void { if( value == _elementVerticalAlign ) return; _elementVerticalAlign = value; _elementVerticalAlignChange = true; invalidateTargetDisplayList(); } //---------------------------------- // radiusX //---------------------------------- /** * @private * Storage property for radiusX. */ private var _radiusX : Number = 100; [Inspectable(category=""General"", type=""Number"", defaultValue=""100"")] /** * The radius to be used on the x axis for the SemiCarouselLayout. * * @default 100 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get radiusX():Number { return _radiusX; } /** * @private */ public function set radiusX( value:Number ):void { if( value == _radiusX ) return; _radiusX = value; invalidateTargetDisplayList(); } //---------------------------------- // radiusY //---------------------------------- /** * @private * Storage property for radiusY. */ private var _radiusY : Number = 0; [Inspectable(category=""General"", type=""Number"", defaultValue=""0"")] /** * The radius to be used on the y axis for the SemiCarouselLayout. * * @default 0 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get radiusY():Number { return _radiusY; } /** * @private */ public function set radiusY( value:Number ):void { if( value == _radiusY ) return; _radiusY = value; invalidateTargetDisplayList(); } //---------------------------------- // radiusZ //---------------------------------- /** * @private * Storage property for radiusZ. */ private var _radiusZ : Number; [Inspectable(category=""General"", type=""Number"", defaultValue=""NaN"")] /** * The radius to be used on the z axis for the SemiCarouselLayout. * *

If a value of NaN is passed the largest of radiusX * or radiusY is used.

* * @default NaN * * @see #radiusX * @see #radiusY * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get radiusZ():Number { return _radiusZ; } /** * @private */ public function set radiusZ( value:Number ):void { if( value == _radiusZ ) return; _radiusZ = value; invalidateTargetDisplayList(); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * * Positions, transforms and sets the size of an element * that will be visible in the layout. */ protected function updateVisibleElementAt( element:IVisualElement, index:int ):void { _displayedElements.push( element ); setElementLayoutBoundsSize( element, false ); _transformCalculator.updateForIndex( index, element, element.width, element.height, _elementHorizontalCenterMultiplier, _elementVerticalCenterMultiplier ); // elementTransformAround( element ); applyColorTransformToElement( element, _transformCalculator.colorTransform ); element.visible = true; } /** * @private */ private function sortElementsByZ( a:IVisualElement, b:IVisualElement ):int { if( getZ( a ) > getZ( b ) ) { return -1; } else if( getZ( a ) < getZ( b ) ) { return 1; } return 0; } /** * @private * * Util function to return the value of the z property * on an element. */ private function getZ( e:IVisualElement ):Number { if( e is GraphicElement ) { return GraphicElement( e ).z; } else { return UIComponent( e ).z; } } /** * @private * * Sets the depth of elements inlcuded in the layout at depths * to display correctly for the z position set with transformAround. * * Also sets the depth of elements that are not included in the layout. * The depth of these is dependent on whether their element index is before * or after the index of the selected element. * * - If their element index is before the selected elements index * they appear beneath all items included in the layout. * * - If their element index is after the selected elements index * they appear above all items included in the layout */ private function updateDepths( depths:Vector. ):void { if( !depths || !depths.length ) return; var animationIndex:int = Math.max( 0, Math.min( Math.round( animationValue ), numElementsInLayout - 1 ) ); var element:IVisualElement; var index:int; var i:int var numBeforeMinDepth:int = 0; var minDepth:int = depths[ 0 ] - 1; var maxDepth:int = depths[ depths.length - 1 ] + 1; const elements:Vector. = new Vector.(); for( i = firstIndexInView; i <= lastIndexInView; i++ ) { index = indicesInLayout[ i ]; element = target.getElementAt( index ); if( !element ) continue; elements.push( element ); } elements.sort( sortElementsByZ ); var num:int = elements.length; for( i = 0; i < num; i++ ) { elements[ i ].depth = depths[ i ]; } // target.validateNow(); // for( i = firstIndexInView; i <= lastIndexInView; i++ ) // { // index = indicesInLayout[ i ]; // element = target.getElementAt( index ); // if( !element ) continue; // if( index < indicesInLayout[ animationIndex ] ) // { // element.depth = _transformCalculator.radiusZ > -1 ? depths.shift() : depths.pop(); // } //// else if ( index > indicesInLayout[ animationIndex ] ) //// { //// element.depth = _direction == SemiCarouselLayoutDirection.CONVEX ? depths.pop() : depths.shift(); //// } // else // { // element.depth = _transformCalculator.radiusZ > -1 ? depths.pop() : depths.shift(); // } // } // // // var numElementsNotInLayout:int = indicesNotInLayout.length; // for( i = 0; i < numElementsNotInLayout; i++ ) // { // if( indicesNotInLayout[ i ] > indicesInLayout[ animationIndex ] ) // { // break; // } // else // { // numBeforeMinDepth++; // } // } // // minDepth -= numBeforeMinDepth - 1; // for( i = 0; i < numElementsNotInLayout; i++ ) // { // element = target.getElementAt( indicesNotInLayout[ i ] ); // if( !element ) continue; // if( indicesNotInLayout[ i ] > indicesInLayout[ animationIndex ] ) // { // element.depth = maxDepth; // maxDepth++; // } // else // { // element.depth = minDepth; // minDepth++; // } // } // // target.validateNow(); } /** * @private * * A convenience method used to transform an element by applying * the current values if the TransforCalulator instance. */ // private function elementTransformAround( element:IVisualElement ):void // { // var halfWidth:Number = element.width / 2; // var halfHeight:Number = element.height / 2; // var offsetX:Number = halfWidth * ( _elementHorizontalCenterMultiplier - 0.5 ) * 2; // var offsetY:Number = halfHeight * ( _elementVerticalCenterMultiplier - 0.5 ) * 2; // // element.transformAround( new Vector3D( element.width / 2, element.height / 2, 0 ), // null, // null, // new Vector3D( _transformCalculator.x - offsetX, _transformCalculator.y - offsetY, _transformCalculator.z ), // null, // new Vector3D( _transformCalculator.xRotation, _transformCalculator.yRotation, 0 ), // new Vector3D( _transformCalculator.x - offsetX, _transformCalculator.y - offsetY, _transformCalculator.z ), // false ); // // } //-------------------------------------------------------------------------- // // Overridden Methods // //-------------------------------------------------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override public function updateDisplayList( unscaledWidth:Number, unscaledHeight:Number):void { // if( this.unscaledWidth != unscaledWidth || this.unscaledHeight != unscaledHeight ) _sizeChanged = true; if( _horizontalAlignChange ) { _horizontalAlignChange = false; // _indicesInViewChanged = true; switch( _horizontalAlign ) { case HorizontalAlign.LEFT : { _horizontalCenterMultiplier = 0; break; } case HorizontalAlign.RIGHT : { _horizontalCenterMultiplier = 1; break; } default : { _horizontalCenterMultiplier = 0.5; } } } if( _verticalAlignChange ) { _verticalAlignChange = false; // _indicesInViewChanged = true; switch( _verticalAlign ) { case VerticalAlign.TOP : { _verticalCenterMultiplier = 0; break; } case VerticalAlign.BOTTOM : { _verticalCenterMultiplier = 1; break; } default : { _verticalCenterMultiplier = 0.5; } } } if( _elementHorizontalAlignChange ) { _elementHorizontalAlignChange = false; // _indicesInViewChanged = true; switch( _elementHorizontalAlign ) { case HorizontalAlign.LEFT : { _elementHorizontalCenterMultiplier = 0; break; } case HorizontalAlign.RIGHT : { _elementHorizontalCenterMultiplier = 1; break; } default : { _elementHorizontalCenterMultiplier = 0.5; } } } if( _elementVerticalAlignChange ) { _elementVerticalAlignChange = false; // _indicesInViewChanged = true; switch( _elementVerticalAlign ) { case VerticalAlign.TOP : { _elementVerticalCenterMultiplier = 0; break; } case VerticalAlign.BOTTOM : { _elementVerticalCenterMultiplier = 1; break; } default : { _elementVerticalCenterMultiplier = 0.5; } } } super.updateDisplayList( unscaledWidth, unscaledHeight ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function updateDisplayListBetween():void { super.updateDisplayListBetween(); if( sizeChangedInLayoutPass ) { // _indicesInViewChanged = true; if( !isNaN( _horizontalAlignOffsetPercent ) ) _horizontalAlignOffset = unscaledHeight * ( _horizontalAlignOffsetPercent / 100 ); if( !isNaN( _verticalAlignOffsetPercent ) ) _verticalAlignOffset = unscaledHeight * ( _verticalAlignOffsetPercent / 100 ); } _transformCalculator.updateForLayoutPass( _horizontalCenterMultiplier, _verticalCenterMultiplier, _rotateX, _rotateY ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function updateDisplayListVirtual():void { super.updateDisplayListVirtual(); var element:IVisualElement; var depths:Vector. = new Vector.(); for each( element in _displayedElements ) { element.visible = false; } _displayedElements = new Vector.(); for( var i:int = firstIndexInView; i <= lastIndexInView; i++ ) { element = target.getVirtualElementAt( indicesInLayout[ i ] ); depths.push( indicesInLayout[ i ] ); updateVisibleElementAt( element, i ); } updateDepths( depths ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function updateDisplayListReal():void { super.updateDisplayListReal(); var element:IVisualElement; var depths:Vector. = new Vector.(); _displayedElements = new Vector.(); for( var i:int = 0; i < numElementsInLayout; i++ ) { element = target.getElementAt( indicesInLayout[ i ] ); if( i >= firstIndexInView && i <= lastIndexInView ) { depths.push( indicesInLayout[ i ] ); updateVisibleElementAt( element, i); } else { element.visible = false; } } updateDepths( depths ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function restoreElement( element:IVisualElement ):void { super.restoreElement( element ); var vector:Vector3D = new Vector3D( 0, 0, 0 ); element.visible = true; element.depth = 0; element.transformAround( vector, null, null, vector, null, vector, vector, false ); applyColorTransformToElement( element, new ColorTransform() ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function updateIndicesInView():void { super.updateIndicesInView(); if( _numUnselectedElements > 0 ) { const ceilIndex:int = Math.ceil( animationValue ); const floorIndex:int = Math.floor( animationValue ); const firstIndexInView:int = Math.max( ceilIndex - _numUnselectedElements, 0 ); var numIndicesInView:int = ( _numUnselectedElements * 2 ) + 1; // If the number of elements on the left are less than _numUnselectedElements if( floorIndex < _numUnselectedElements ) { numIndicesInView -= _numUnselectedElements - floorIndex; } // If we are mid transition, we don't need the last item else if( floorIndex != animationValue ) { numIndicesInView -= 1; } // If we are at the end of the list of elements if( floorIndex + _numUnselectedElements >= numElementsInLayout ) { numIndicesInView -= _numUnselectedElements - ( ( numElementsInLayout - 1 ) - floorIndex ); } indicesInView( firstIndexInView, numIndicesInView ); } else { indicesInView( 0, numElementsInLayout ); } } } } import flash.geom.ColorTransform; import flash.geom.Point; import flash.geom.Vector3D; import mx.core.IVisualElement; import spark.layouts.CarouselLayout; internal class TransformValues { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function TransformValues( layout:CarouselLayout ) { _layout = layout; _colorTransform = new ColorTransform(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var _layout : CarouselLayout; private var _index : int; private var _indexOffset : Number; // Center private var _cx : Number; private var _cy : Number; // AlignOffset private var _ho : Number; private var _vo : Number; private var _rx : Number; private var _ry : Number; private var _rz : Number; // Number of items private var _ni : Number; private var _an : Number; private var _c : int; private var _ca : Number; private var _rotY : int; private var _rotX : int; private var _oy:Number; private var _ox:Number; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // x //---------------------------------- /** * @private * Storage property for x. */ private var _x:Number; // /** // * x // * // * @langversion 3.0 // * @playerversion Flash 10 // * @playerversion AIR 1.5 // * @productversion Flex 4 // */ // public function get x():Number // { // return _x; // } //---------------------------------- // y //---------------------------------- /** * @private * Storage property for y. */ private var _y:Number; // /** // * y // * // * @langversion 3.0 // * @playerversion Flash 10 // * @playerversion AIR 1.5 // * @productversion Flex 4 // */ // public function get y():Number // { // return _y; // } //---------------------------------- // z //---------------------------------- /** * @private * Storage property for z. */ private var _z:Number; // /** // * z // * // * @langversion 3.0 // * @playerversion Flash 10 // * @playerversion AIR 1.5 // * @productversion Flex 4 // */ // public function get z():Number // { // return _z; // } //---------------------------------- // xRotation //---------------------------------- /** * @private * Storage property for xRotation. */ private var _xRotation:Number; // /** // * xRotation // * // * @langversion 3.0 // * @playerversion Flash 10 // * @playerversion AIR 1.5 // * @productversion Flex 4 // */ // public function get xRotation():Number // { // return _xRotation; // } //---------------------------------- // yRotation //---------------------------------- /** * @private * Storage property for yRotation. */ private var _yRotation:Number; /** * yRotation * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ // public function get yRotation():Number // { // return _yRotation; // } // // public function get radiusZ():Number { return _rz; } //---------------------------------- // colorTransform //---------------------------------- /** * @private * Storage property for colorTransform. */ private var _colorTransform:ColorTransform; /** * colorTransform * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get colorTransform():ColorTransform { return _colorTransform; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * updateForLayoutPass * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function updateForLayoutPass( centerMultiplierX:Number, centerMultiplierY:Number, rotX:int, rotY:int ):void { _index = Math.floor( _layout.animationValue ); _indexOffset = _layout.animationValue - _index; _cx = _layout.unscaledWidth * centerMultiplierX; _cy = _layout.unscaledHeight * centerMultiplierY; _ho = _layout.horizontalAlignOffset; _vo = _layout.verticalAlignOffset; _c = _layout.depthColor; _ca = _layout.depthColorAlpha / 100; if( _c < 0 ) { _colorTransform.redMultiplier = _colorTransform.greenMultiplier = _colorTransform.blueMultiplier = 1; _colorTransform.redOffset = _colorTransform.greenOffset = _colorTransform.blueOffset = _colorTransform.alphaOffset = 0; } _rx = _layout.radiusX; _ry = _layout.radiusY; _rz = _layout.radiusZ; if( isNaN( _rz ) ) _rz = Math.abs( ( Math.abs( _rx ) > Math.abs( _ry ) ) ? _rx : _ry ); _rotY = rotY; _rotX = rotX; const numElements:int = _layout.numUnselectedElements < 0 ? 0 : _layout.numUnselectedElements; _an = numElements ? _layout.angle / ( numElements * 2 ) : _layout.angle / _layout.numElementsInLayout; } /** * circular * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ private function layout( index:Number ):void { const degree:Number = _an * index; const radian:Number = degree * Math.PI / 180; _x = _cx + _ho + ( Math.sin( radian ) * _rx ); _y = _cy + _vo + ( Math.sin( radian ) * _ry ); _z = _rz - ( Math.cos( radian ) * _rz ); _yRotation = _rx && _rotY != 0 ? -( angle( _x, _z, _cx + _ho, _rz ) - 90 ) * _rotY : 0; _xRotation = _ry && _rotX != 0 ? ( angle( _y , _z, _cy + _vo, _rz ) - 90 ) * _rotX : 0; if( _rz < 0 ) { if( _yRotation ) _yRotation += 180; if( _xRotation ) _xRotation += 180; } } public function angle( x1:Number, y1:Number, x2:Number, y2:Number ):Number { return Math.atan2( y2 - y1, x2 - x1 ) * ( 180 / Math.PI ); } /** * updateForIndex * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function updateForIndex( i:int, element:IVisualElement, width:Number, height:Number, hMultiplier:Number, vMultiplier:Number ):void { _ox = ( width / 2 ) * ( hMultiplier - 0.5 ) * 2; _oy = ( height / 2 ) * ( vMultiplier - 0.5 ) * 2; layout( ( i - _index ) - _indexOffset ); if( _c > -1 ) { const radian:Number = ( _layout.angle / 2 ) * Math.PI / 180; const maxDepth:Number = _rz - ( Math.cos( radian ) * _rz ) const v:Number = ( _z / maxDepth ) * _ca; _colorTransform.color = _c; _colorTransform.redOffset *= v; _colorTransform.greenOffset *= v; _colorTransform.blueOffset *= v; _colorTransform.redMultiplier = _colorTransform.greenMultiplier = _colorTransform.blueMultiplier = 1 - v; } element.transformAround( new Vector3D( width / 2, height / 2, 0 ), null, null, new Vector3D( _x - _ox, _y - _oy, _z ), null, new Vector3D( _xRotation, _yRotation, 0 ), new Vector3D( _x - _ox, _y - _oy, _z ), false ); } }",12078,True,2523.306752251538,median "module HeapLemmasForSplitting where open import HeapPropertiesDefs open import Silica import Relation.Binary.PropositionalEquality as Eq import Context open import Data.List.Relation.Unary.All import Relation.Unary import Data.List.Properties import Data.List open import Data.Sum open import Data.Maybe open import Data.List.Membership.DecSetoid ≡-decSetoid open import Data.List.Relation.Unary.Any open import Data.Empty open TypeEnvContext ----------- PROPERTIES OF SPLITTING ----------- -- The results of splitting are always compatible. splitCompatibility : ∀ {Γ} → ∀ {t₁ t₂ t₃ : Type} → Γ ⊢ t₁ ⇛ t₂ / t₃ → t₂ ⟷ t₃ splitCompatibility voidSplit = voidCompat splitCompatibility booleanSplit = booleanCompat splitCompatibility (unownedSplit {Γ} {t₁} {t₂} {t₃} eqNames1 eqNames2 eqPerms t3IsUnowned) = symCompat (unownedCompat t3IsUnowned (Eq.trans (Eq.sym eqNames2) eqNames1)) splitCompatibility (shared-shared-shared {Γ} {t} eq) = sharedCompat eq eq refl splitCompatibility (owned-shared notAsset) = sharedCompat refl refl refl splitCompatibility (states-shared x) = sharedCompat refl refl refl compatibleContractsHaveSameNames : ∀ {T : Type} → ∀ {t : Tc} → ∀ {t' : Tc} → contractType t ⟷ T → T ≡ contractType t' → Tc.contractName t ≡ Tc.contractName t' compatibleContractsHaveSameNames {T} {t} {t'} (symCompat compat) refl = sym (compatibleContractsHaveSameNames compat refl) compatibleContractsHaveSameNames {T} {t} {t'} (unownedCompat x x₁) refl = x₁ compatibleContractsHaveSameNames {T} {t} {t'} (sharedCompat x x₁ x₂) refl = x₂ typesCompatibleWithContractsAreContracts : ∀ {T : Type} → ∀ {t : Tc} → contractType t ⟷ T → ∃[ t' ] (T ≡ contractType t') typesCompatibleWithContractsAreContracts {T} {t} (symCompat (symCompat compat)) = typesCompatibleWithContractsAreContracts compat typesCompatibleWithContractsAreContracts {(contractType (tc _ _))} {(tc _ _)} (symCompat (unownedCompat {C} {C'} {perm} {perm'} x x₁)) = ⟨ tc C perm , refl ⟩ typesCompatibleWithContractsAreContracts {(contractType (tc _ _))} {(tc _ _)} (symCompat (sharedCompat {t} {t'} x x₁ x₂)) = ⟨ t , refl ⟩ typesCompatibleWithContractsAreContracts {T} {t} (unownedCompat {C} {C'} {perm} {perm'} refl refl) = ⟨ tc C perm' , refl ⟩ typesCompatibleWithContractsAreContracts {T} {t} (sharedCompat {tc C Shared} {tc C' Shared} refl refl refl) = ⟨ tc C Shared , refl ⟩ splittingRespectsHeap : ∀ {Γ} → ∀ {T t₁ t₂ t₃ : Type} → Γ ⊢ t₁ ⇛ t₂ / t₃ → T ⟷ t₁ → (T ⟷ t₂) × (T ⟷ t₃) splittingRespectsHeap {Γ} {T} {(base Void)} {(base Void)} {(base Void)} voidSplit consis = ⟨ consis , consis ⟩ splittingRespectsHeap {Γ} {T} {.(base Boolean)} {.(base Boolean)} {.(base Boolean)} booleanSplit consis = ⟨ consis , consis ⟩ -- t₁ => t₁ / t₃ because t₃ is Unowned. splittingRespectsHeap {Γ} {T} {contractType t₁} {contractType t₂} {contractType t₃} (unownedSplit {Γ} {t₁} {t₂} {t₃} x x₁ x₂ x₃) (symCompat consis) rewrite (eqContractTypes x₂ x) | (proj₂ (typesCompatibleWithContractsAreContracts {T} {t₂} consis)) = let TIsContractTypeEx = typesCompatibleWithContractsAreContracts {T} consis -- T is a contractType. TContractType = proj₁ TIsContractTypeEx TIsContractType = proj₂ TIsContractTypeEx compatTypes = (compatibleContractsHaveSameNames consis TIsContractType) C = Tc.contractName t₃ C' = Tc.contractName TContractType in ⟨ symCompat ( Eq.subst (λ a → contractType t₂ ⟷ a) TIsContractType consis) , symCompat (unownedCompat x₃ (Eq.trans (Eq.sym x₁) compatTypes)) ⟩ -- t1 => t1 / Unowned splittingRespectsHeap {Γ} {(contractType (tc C perm))} {contractType (tc C' perm')} {contractType t₂} {contractType t₃} (unownedSplit x x₁ x₂ x₃) (unownedCompat x₄ x₅) = ⟨ unownedCompat x₄ (Eq.trans x₅ x), unownedCompat x₄ (Eq.trans x₅ x₁) ⟩ splittingRespectsHeap {Γ} {(contractType t)} {contractType t₁} {contractType t₂} {contractType t₃} (unownedSplit x x₁ x₂ x₃) (sharedCompat t₁Shared t₂Shared t₁t₂Names) rewrite x₂ = ⟨ sharedCompat t₁Shared t₂Shared (Eq.trans t₁t₂Names x) , symCompat (unownedCompat x₃ (Eq.trans (Eq.sym x₁) (Eq.sym t₁t₂Names))) ⟩ splittingRespectsHeap {Γ} {T} {.(contractType _)} {.(contractType _)} {.(contractType _)} (shared-shared-shared x) consis = ⟨ consis , consis ⟩ -- Owned => Shared / Shared. Requires that T be Unowned. splittingRespectsHeap {Γ} {T} {contractType (tc _ Owned)} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (owned-shared x) (symCompat (symCompat consis)) = splittingRespectsHeap (owned-shared x) consis splittingRespectsHeap {Γ} {.(contractType (tc _ _))} {contractType (tc _ Owned)} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (owned-shared x) (symCompat (unownedCompat () x₂)) splittingRespectsHeap {Γ} {.(contractType _)} {contractType (tc _ Owned)} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (owned-shared x) (symCompat (sharedCompat () x₂ x₃)) splittingRespectsHeap {Γ} {.(contractType (tc _ _))} {.(contractType (tc _ Owned))} {.(contractType (tc _ Shared))} {.(contractType (tc _ Shared))} (owned-shared x) (unownedCompat x₁ x₂) = ⟨ unownedCompat x₁ x₂ , unownedCompat x₁ x₂ ⟩ splittingRespectsHeap {Γ} {.(contractType _)} {.(contractType (tc _ Owned))} {.(contractType (tc _ Shared))} {.(contractType (tc _ Shared))} (owned-shared x) (sharedCompat x₁ () x₃) -- States => Shared / Shared. Requires that T be Unowned. splittingRespectsHeap {Γ} {T} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (symCompat (symCompat consis)) = splittingRespectsHeap (states-shared x) consis splittingRespectsHeap {Γ} {.(contractType (tc _ _))} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (symCompat (unownedCompat () x₃)) splittingRespectsHeap {Γ} {.(contractType _)} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (symCompat (sharedCompat () x₃ x₄)) splittingRespectsHeap {Γ} {.(contractType (tc _ _))} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (unownedCompat x₁ x₂) = ⟨ unownedCompat x₁ x₂ , unownedCompat x₁ x₂ ⟩ splittingRespectsHeap {Γ} {.(contractType _)} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (sharedCompat x₂ () x₄) splitSymmetric : ∀ {T T'} → T ⟷ T' → T' ⟷ T splitSymmetric {T} {T'} compat = symCompat compat -- =================== LEMMAS RELATED TO HEAP CONSISTENCY ================= -- If a location is in ρ, then there is a corresponding item in envTypesList. findLocationInEnvTypes : ∀ {Σ Δ l o T forbiddenRefs} → (envTypesList : List Type) → EnvTypes Σ (Δ ,ₗ l ⦂ T) o forbiddenRefs envTypesList → IsConnectedTypeList envTypesList → (RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal o) → T ∈ₜ envTypesList × All (λ T' → (T' ≢ T) → T ⟷ T') envTypesList -- The argument will have the form: look, I found T in envTypes, so it must be compatible with everything in fieldTypes already. findLocationInEnvTypes {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T} .(T' ∷ R) (envTypesConcatMatchFound {R = R} {l = l₁} {T = T'} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = forbiddenRefs} .(Δ ,ₗ l ⦂ T) o envTypes l₁HasTypeT l₁NotForbidden) (consTypeList firstConnected restConnected) lInρ with l ≟ l₁ ... | yes lEql₁ = -- We must have T' ≡ T because we looked up l in (Δ ,ₗ l ⦂ T). let TInEnvTypesList = here (Eq.sym TEqContractTypet₁) TCompatWithRest = transformConnected R (Eq.subst (λ a → All (λ T' → a ⟷ T') R) TEqContractTypet₁ firstConnected) in ⟨ TInEnvTypesList , (λ TNeqT' → ⊥-elim (TNeqT' (TEqContractTypet₁))) ∷ TCompatWithRest ⟩ -- Eq.subst (λ a → All (λ a → T ⟷ a) (T' ∷ R)) TEqContractTypet₁ firstConnected ⟩ where lInΔ' : ((StaticEnv.locEnv Δ) , l ⦂ T) ∋ l ⦂ T lInΔ' = Z TEqContractTypet₁ : T' ≡ T TEqContractTypet₁ = contextLookupUnique l₁HasTypeT (Eq.subst (λ a → (StaticEnv.locEnv Δ) TypeEnvContext., l ⦂ T ∋ a ⦂ T) lEql₁ lInΔ') transformConnected : ∀ L → All (λ T' → T ⟷ T') L → All (λ T' → (T' ≢ T) → T ⟷ T') L transformConnected L [] = [] transformConnected (T' ∷ L) (h ∷ r) = (λ tNeqT' → h) ∷ (transformConnected L r) ... | no lNeql₁ = -- envTypesList is T ∷ R, but T is not the one we were interested in. l ⦂ o is in ρ, but not at the end. -- Eventually we'll look up l in (Δ ,ₗ l ⦂ T) and find T. let lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ lNeql₁ recurse = findLocationInEnvTypes {re μ ρ φ ψ} {Δ} {l} {o} {T} R envTypes restConnected lInRestOfρ TInR = proj₁ recurse TCompatT' = Data.List.Relation.Unary.All.lookup firstConnected TInR in ⟨ there TInR , (λ TNeqT' → symCompat TCompatT') ∷ proj₂ recurse ⟩ -- firstConnected ⟩ findLocationInEnvTypes {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T} envTypesList (envTypesConcatMatchNotFound {R = .envTypesList} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = forbiddenRefs} .(Δ ,ₗ l ⦂ T) o envTypes lNotInΔ') connected lInρ = let lNeql₁ = ≢-sym (∉dom-≢ lNotInΔ') lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ lNeql₁ in findLocationInEnvTypes envTypesList envTypes connected lInRestOfρ findLocationInEnvTypes {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {o} {T} envTypesList (envTypesConcatMismatch {R = .envTypesList} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = forbiddenRefs} .(Δ ,ₗ l ⦂ T) o o' oNeqo' envTypes) connected lInρ = let -- from o ≢ o' I need to prove that objVal o ≢ objVal o' -- so I assume objVal o ≡ objVal o' and derive o ≡ o', which is a contradiction. oExprNeqo'Expr = λ objValsEq → (objValInjective oNeqo') (Eq.sym objValsEq) lInRestOfρ = IndirectRefContext.irrelevantReductionsInValuesOK lInρ oExprNeqo'Expr in findLocationInEnvTypes envTypesList envTypes connected lInRestOfρ -- If a list of types was all compatible with the env types for (Δ ,ₗ l ⦂ T), then everything in that list is compatible with T. prevCompatibilityImpliesCompatibility : ∀ {Σ Δ l o T} → (RT : RefTypes Σ (Δ ,ₗ l ⦂ T) o) → (TL : List Type) → All (λ T → All (_⟷_ T) TL) (RefTypes.envTypesList RT) → IsConnectedTypeList (RefTypes.envTypesList RT) → (RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal o) → All (_⟷_ (T)) TL prevCompatibilityImpliesCompatibility {Σ} {Δ} {l} {o} {T} RT TL envTypesCompatibleWithTypes connected lInρ = let TInEnvTypes = proj₁ (findLocationInEnvTypes (RefTypes.envTypesList RT) (RefTypes.envTypes RT) connected lInρ) in Data.List.Relation.Unary.All.lookup envTypesCompatibleWithTypes TInEnvTypes envTypesForbiddenRefsObserved : ∀ {l forbiddenRefs T T' Σ R} → (Δ : StaticEnv) → (o : ObjectRef) → l ∈ forbiddenRefs → EnvTypes Σ (Δ ,ₗ l ⦂ T) o forbiddenRefs R → EnvTypes Σ (Δ ,ₗ l ⦂ T') o forbiddenRefs R -- We previously found l₁ ⦂ o at the END of ρ, and found l₁ : T in (Δ ,ₗ l ⦂ T). By ""l₁NotInForbiddenRefs"" we may derive l ≢ l₁. -- ρ , l₁ : objVal o -- WTS: when we look up l₁ in (Δ ,ₗ l ⦂ T'), we'll still get objVal o. envTypesForbiddenRefsObserved {l} {forbiddenRefs} {T} {T'} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {.(T₁ ∷ R)} Δ o lInLs envTypes@(envTypesConcatMatchFound {R = R} {l = l₁} {T = T₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = forbiddenRefs} .(Δ ,ₗ l ⦂ T) .o origEnvTypes l₁HasTypeT₁WithL l₁NotInForbiddenRefs) = let l₁NeqL : l₁ ≢ l l₁NeqL = listNoncontainment l₁NotInForbiddenRefs lInLs l₁HasSameTypeInNewContext = irrelevantExtensionsOK {y = l} {t' = T'} (irrelevantReductionsOK l₁HasTypeT₁WithL l₁NeqL) l₁NeqL recursiveCall = envTypesForbiddenRefsObserved {l = l} {T = T} {T' = T'} Δ o (there lInLs) origEnvTypes in envTypesConcatMatchFound {R = R} (Δ ,ₗ l ⦂ T') o recursiveCall l₁HasSameTypeInNewContext l₁NotInForbiddenRefs envTypesForbiddenRefsObserved {l} {forbiddenRefs} {T} {T'} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {R} Δ o lInLs (envTypesConcatMatchNotFound {R = .R} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T) .o origEnvTypes l₁NotInDomΔ') = let prevEnvTypesObserved = envTypesForbiddenRefsObserved Δ o lInLs origEnvTypes in envTypesConcatMatchNotFound (Δ ,ₗ l ⦂ T') o prevEnvTypesObserved (∉domPreservation l₁NotInDomΔ') envTypesForbiddenRefsObserved {l} {forbiddenRefs} {T} {T'} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {R} Δ o lInLs (envTypesConcatMismatch {R = .R} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T) .o o' oNeqO' origEnvTypes) = let prevEnvTypesObserved = envTypesForbiddenRefsObserved Δ o lInLs origEnvTypes in envTypesConcatMismatch (Δ ,ₗ l ⦂ T') o o' oNeqO' prevEnvTypesObserved envTypesForbiddenRefsObserved {l} {forbiddenRefs} {T} {T'} {.(re μ IndirectRefContext.∅ φ ψ)} {.[]} Δ o lInLs (envTypesEmpty {μ = μ} {φ = φ} {ψ = ψ} {Δ = .(Δ ,ₗ l ⦂ T)} {o = .o} {forbiddenRefs = .forbiddenRefs}) = envTypesEmpty -- Inversion for isConnected isConnectedImpliesOsConnected : ∀ {Σ Δ o R} → IsConnected Σ Δ o R → IsConnectedTypeList (RefTypes.oTypesList R) isConnectedImpliesOsConnected {Σ} {Δ} {o} {R} (isConnected R cl _ _ _ ) = cl singleElementListsAreConnected : (T : Type) → IsConnectedTypeList [ T ] singleElementListsAreConnected T = consTypeList [] (emptyTypeList refl) -- Basic properties of contexts ctxTypesExtension : ∀ {Δ o T} → [ T ] ≡ ctxTypes (Δ , o ⦂ T) o ctxTypesExtension {Δ} {o} {T} with o ≟ o ... | yes oEq = refl ... | no oNeq = ⊥-elim (oNeq refl) ctxTypesExtensionNeq : ∀ {Δ o o' T} → o' ≢ o → ctxTypes (Δ , o ⦂ T) o' ≡ ctxTypes Δ o' ctxTypesExtensionNeq {Δ} {o} {o'} {T} oNeq with o' ≟ o ... | yes p = ⊥-elim (oNeq p) ... | no ¬p = refl t₁CompatibilityImpliest₂Compatibility : ∀ {Γ TL T₁ T₂ T₃} → All (λ T' → T₁ ⟷ T') TL → Γ ⊢ T₁ ⇛ T₂ / T₃ → All (λ T' → T₂ ⟷ T') TL t₁CompatibilityImpliest₂Compatibility {Γ} {.[]} {T₁} {T₂} {T₃} [] spl = [] t₁CompatibilityImpliest₂Compatibility {Γ} {.(x ∷ xs)} {T₁} {T₂} {T₃} (_∷_ {x = x} {xs = xs} TCompat restCompat) spl = let TCompat' = proj₁ (splittingRespectsHeap spl (symCompat TCompat)) in (symCompat TCompat') ∷ t₁CompatibilityImpliest₂Compatibility restCompat spl t₁CompatibilityImpliest₃Compatibility : ∀ {Γ TL T₁ T₂ T₃} → All (λ T' → T₁ ⟷ T') TL → Γ ⊢ T₁ ⇛ T₂ / T₃ → All (λ T' → T₃ ⟷ T') TL t₁CompatibilityImpliest₃Compatibility {Γ} {.[]} {T₁} {T₂} {T₃} [] spl = [] t₁CompatibilityImpliest₃Compatibility {Γ} {.(x ∷ xs)} {T₁} {T₂} {T₃} (_∷_ {x = x} {xs = xs} TCompat restCompat) spl = let TCompat' = proj₂ (splittingRespectsHeap spl (symCompat TCompat)) in (symCompat TCompat') ∷ t₁CompatibilityImpliest₃Compatibility restCompat spl connectedTypeListsAreConnected : ∀ {T Ts} → IsConnectedTypeList Ts → (TIncluded : T ∈ₜ Ts) → (T'Included : T ∈ₜ Ts) → TIncluded ≢ T'Included → T ⟷ T connectedTypeListsAreConnected {.x} {.(x ∷ xs)} TsConnected (here {x = x} {xs = xs} refl) (here {x = .x} {xs = .xs} refl) TNeqT' = ⊥-elim (TNeqT' refl) connectedTypeListsAreConnected {T} {.(T ∷ D)} (consTypeList {T = .T} {D = D} TConnectedToRest TsConnected) (here {x = .T} {xs = .D} refl) (there {x = .T} {xs = .D} T'InTs) TNeqT' = Data.List.Relation.Unary.All.lookup TConnectedToRest T'InTs connectedTypeListsAreConnected {T} {.(T ∷ D)} (consTypeList {T = .T} {D = D} TConnectedToRest TsConnected) (there {x = .T} {xs = .D} TInTs) (here {x = .T} {xs = .D} refl) TNeqT' = Data.List.Relation.Unary.All.lookup TConnectedToRest TInTs connectedTypeListsAreConnected {T} {.(x ∷ xs)} (consTypeList {T = .x} {D = .xs} x₁ restConnected) (there {x = x} {xs = xs} TInTs) (there {x = .x} {xs = .xs} T'InTs) TNeqT' = connectedTypeListsAreConnected restConnected TInTs T'InTs λ prfsEqual → TNeqT' (Eq.cong there prfsEqual) {- record EnvTypesForSplitResult (Σ : RuntimeEnv) (Δ : StaticEnv) (T₂ : Type) (T₃ : Type) (l : IndirectRef) (o : ObjectRef) : Set where field Ts' : List Type T₂Compat : (All (λ T' → T₂ ⟷ T') Ts') et : (EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o forbiddenRefs Ts') connected : (IsConnectedTypeList Ts') externalCompat : (λ T' → All (λ T'' → T' ⟷ T'') Ts → All (λ T'' → T' ⟷ T'') Ts') -} -- Trying to assume that T₁ is compatible with all the Ts is too strong, since T₁ may be in the Ts. -- What do I actually need here I need to show that T₂ is compatible with all the new types. -- So envTypesForSplit : ∀ {Γ Σ Δ l o T₁ T₂ T₃ Ts forbiddenRefs} → EnvTypes Σ (Δ ,ₗ l ⦂ T₁) o forbiddenRefs Ts → (RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal o) → All (λ T' → (T' ≢ T₁) → T₁ ⟷ T') Ts → IsConnectedTypeList Ts → Γ ⊢ T₁ ⇛ T₂ / T₃ → ∃[ Ts' ] ((EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o forbiddenRefs Ts') × (All (λ T' → T₂ ⟷ T') Ts') × (IsConnectedTypeList Ts') × (∀ T' → All (λ T'' → T' ⟷ T'') Ts → All (λ T'' → T' ⟷ T'') Ts')) envTypesForSplit {Γ} {Σ@.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {.(T₄ ∷ R)} {forbiddenRefs} origMatch@(envTypesConcatMatchFound {R = R} {l = l₁} {T = T₄} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} .(Δ ,ₗ l ⦂ T₁) o origEnvTypes lookupResult l₁NotForbidden) lInρ (T₁Connected ∷ RConnected) (consTypeList firstConnected restConnected) spl with l₁ ≟ l ... | yes eq = -- The last step in the proof of EnvTypes (ρ , l₁ ⦂ o) (Δ ,ₗ l ⦂ T₃) o T₁∷R is that we looked up l₁ and prepended the result to the rest of the Ts. -- If l₁ ≡ l, then Ts' is T₃ ∷ R. Otherwise, we found l₁ ⦂ T₄ in Δ and Ts' is T₄ ∷ (recurse with the rest). ⟨ Ts' , ⟨ envTypesTs' , ⟨ T₂CompatWithT₃ ∷ T₂CompatWithRestOfEnvTypes , ⟨ (consTypeList T₃CompatWithRestOfEnvTypes restConnected) , externalCompat ⟩ ⟩ ⟩ ⟩ where Ts'' = R Ts' = T₃ ∷ Ts'' -- WTS: (EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o Ts') × All (λ T' → T ⟷ T') Ts') lookupResultWithl : (StaticEnv.locEnv Δ , l ⦂ T₁) ∋ l ⦂ T₄ lookupResultWithl = Eq.subst (λ a → StaticEnv.locEnv Δ , l ⦂ T₁ ∋ a ⦂ T₄) eq lookupResult origEnvTypesWithL : EnvTypes (re μ ρ φ ψ) (Δ ,ₗ l₁ ⦂ T₁) o (l₁ ∷ forbiddenRefs) R origEnvTypesWithL = Eq.subst (λ a → EnvTypes (re μ ρ φ ψ) (Δ ,ₗ a ⦂ T₁) o (l₁ ∷ forbiddenRefs) R) (Eq.sym eq) origEnvTypes forbiddenOK = envTypesForbiddenRefsObserved {T' = T₃} Δ o (here refl) origEnvTypesWithL forbiddenOKInL₁ : EnvTypes (re μ ρ φ ψ) (Δ ,ₗ l ⦂ T₃) o (l₁ ∷ forbiddenRefs) R forbiddenOKInL₁ = Eq.subst (λ a → EnvTypes (re μ ρ φ ψ) (Δ ,ₗ a ⦂ T₃) o (l₁ ∷ forbiddenRefs) R) eq forbiddenOK -- We already know that the first match in ρ for o is l, so the new Ts' has to be right. envTypesTs' : EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o forbiddenRefs Ts' envTypesTs' = envTypesConcatMatchFound {l = l₁} (Δ ,ₗ l ⦂ T₃) o forbiddenOKInL₁ (Eq.subst (λ a → StaticEnv.locEnv Δ , a ⦂ T₃ ∋ l₁ ⦂ T₃) eq Z) l₁NotForbidden T₄EqT₁ : T₄ ≡ T₁ T₄EqT₁ = contextLookupUnique lookupResultWithl Z T₄CompatWithRestOfEnvTypes = firstConnected T₁CompatWithRestOfEnvTypes = Eq.subst (λ a → All (λ T' → a ⟷ T') R) T₄EqT₁ T₄CompatWithRestOfEnvTypes T₂CompatWithRestOfEnvTypes : All (λ T' → T₂ ⟷ T') R T₂CompatWithRestOfEnvTypes = t₁CompatibilityImpliest₂Compatibility T₁CompatWithRestOfEnvTypes spl T₂CompatWithT₃ = splitCompatibility spl -- Need to prove everything in R is connected to T₃, given that everything in R is connected to T₄ (≡ T₁). -- Follows from splittingRespectsHeap. T₃CompatWithRestOfEnvTypes : All (λ T' → T₃ ⟷ T') R T₃CompatWithRestOfEnvTypes = t₁CompatibilityImpliest₃Compatibility T₁CompatWithRestOfEnvTypes spl externalCompat : (T' : Type) → All (λ T'' → T' ⟷ T'') (T₄ ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externalCompat T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = let T'CompatT₁ = Eq.subst (λ a → T' ⟷ a) T₄EqT₁ px T'CompatT₃ = proj₂ (splittingRespectsHeap spl T'CompatT₁) in T'CompatT₃ ∷ T'CompatWithTs envTypesForSplit {Γ} {Σ@.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {.(T₄ ∷ R)} {forbiddenRefs} origMatch@(envTypesConcatMatchFound {R = R} {l = l₁} {T = T₄} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} .(Δ ,ₗ l ⦂ T₁) o origEnvTypes lookupResult l₁NotForbidden) lInρ (T₁Connected ∷ RConnected) allConnected@(consTypeList firstConnected restConnected) spl | no nEq with T₄ ≟t T₁ ... | yes T₄EqT₁ = ⟨ Ts' , ⟨ envTypesTs' , ⟨ Ts'Compat , ⟨ consTypeList T₄CompatWithR' (proj₁ (proj₂ (proj₂ (proj₂ R'WithProof)))) , externCompatibility' ⟩ ⟩ ⟩ ⟩ where -- Because we're in envTypeConcatMatchFound, l₁ ⦂ o was at the end of the context, and we found l₁ ⦂ T₄ in Δ , l ⦂ T₁. -- But l ≢ l₁, so we will be able to find l₁ ⦂ T₄ in Δ and use the same rule. -- However, there may be l's in ρ, which may result in a different R than before! Some T₁'s may be replaced with T₃'s. lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ (≢-sym nEq) R'WithProof = envTypesForSplit origEnvTypes lInRestOfρ RConnected restConnected spl R' = proj₁ R'WithProof Ts' = T₄ ∷ R' l₁InΔ : ((StaticEnv.locEnv Δ) , l ⦂ T₃) ∋ l₁ ⦂ T₄ l₁InΔ = irrelevantExtensionsOK {t = T₄} {t' = T₃} (irrelevantReductionsOK lookupResult nEq) nEq envTypesTs' = envTypesConcatMatchFound (Δ ,ₗ l ⦂ T₃) o (proj₁ (proj₂ R'WithProof)) l₁InΔ l₁NotForbidden -- Previously, we knew that T₄ was compatible with everything in R. -- Specificially, we have T₁Connected : (T₄ ≢ T₁) → T₁ ⟷ T₄. -- Everything that was compatible with T₁ has to be compatible with T₂. foundLocationInRest = findLocationInEnvTypes R origEnvTypes restConnected lInRestOfρ T₁InR : T₁ ∈ₜ R T₁InR = proj₁ foundLocationInRest proofsNotEq : (there T₁InR) ≢ (here (Eq.sym T₄EqT₁)) proofsNotEq () T₁CompatWithT₁ : T₁ ⟷ T₁ T₁CompatWithT₁ = connectedTypeListsAreConnected allConnected (there T₁InR) (here (Eq.sym T₄EqT₁)) proofsNotEq -- We found another copy of T₁ in the original envTypes. But we know the original envTypes was all connected. -- There has to be ANOTHER copy of T₁ in R. We know THIS T₁ is connected to THAT T₁ because THIS T₁ is connected to everything in R. T₂CompatWithT₁ : T₂ ⟷ T₁ T₂CompatWithT₁ = symCompat (proj₁ (splittingRespectsHeap spl T₁CompatWithT₁)) T₂CompatWithT₄ = Eq.subst (λ a → T₂ ⟷ a) (Eq.sym T₄EqT₁) T₂CompatWithT₁ T₂CompatWithR' = proj₁ (proj₂ (proj₂ R'WithProof)) Ts'Compat = T₂CompatWithT₄ ∷ T₂CompatWithR' externCompatibility = proj₂ (proj₂ (proj₂ (proj₂ R'WithProof))) T₄CompatWithR' : All (λ T' → T₄ ⟷ T') R' T₄CompatWithR' = externCompatibility T₄ firstConnected externCompatibility' : (T' : Type) → All (λ T'' → T' ⟷ T'') (T₄ ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externCompatibility' T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = px ∷ externCompatibility T' T'CompatWithTs ... | no T₄NeqT₁ = ⟨ Ts' , ⟨ envTypesTs' , ⟨ Ts'Compat , ⟨ consTypeList T₄CompatWithR' (proj₁ (proj₂ (proj₂ (proj₂ R'WithProof)))) , externCompatibility' ⟩ ⟩ ⟩ ⟩ where -- Because we're in envTypeConcatMatchFound, l₁ ⦂ o was at the end of the context, and we found l₁ ⦂ T₄ in Δ , l ⦂ T₁. -- But l ≢ l₁, so we will be able to find l₁ ⦂ T₄ in Δ and use the same rule. -- However, there may be l's in ρ, which may result in a different R than before! Some T₁'s may be replaced with T₃'s. lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ (≢-sym nEq) R'WithProof = envTypesForSplit origEnvTypes lInRestOfρ RConnected restConnected spl R' = proj₁ R'WithProof Ts' = T₄ ∷ R' l₁InΔ : ((StaticEnv.locEnv Δ) , l ⦂ T₃) ∋ l₁ ⦂ T₄ l₁InΔ = irrelevantExtensionsOK {t = T₄} {t' = T₃} (irrelevantReductionsOK lookupResult nEq) nEq envTypesTs' = envTypesConcatMatchFound (Δ ,ₗ l ⦂ T₃) o (proj₁ (proj₂ R'WithProof)) l₁InΔ l₁NotForbidden -- Previously, we knew that T₄ was compatible with everything in R. -- Specificially, we have T₁Connected : (T₄ ≢ T₁) → T₁ ⟷ T₄. -- Everything that was compatible with T₁ has to be compatible with T₂. T₄CompatWithT₁ : T₄ ⟷ T₁ T₄CompatWithT₁ = symCompat (T₁Connected T₄NeqT₁) T₄CompatWithT₂ : T₄ ⟷ T₂ T₄CompatWithT₂ = proj₁ (splittingRespectsHeap spl T₄CompatWithT₁) T₂CompatWithT₄ = symCompat T₄CompatWithT₂ T₂CompatWithR' = proj₁ (proj₂ (proj₂ R'WithProof)) Ts'Compat = T₂CompatWithT₄ ∷ T₂CompatWithR' externCompatibility = proj₂ (proj₂ (proj₂ (proj₂ R'WithProof))) T₄CompatWithR' : All (λ T' → T₄ ⟷ T') R' T₄CompatWithR' = externCompatibility T₄ firstConnected externCompatibility' : (T' : Type) → All (λ T'' → T' ⟷ T'') (T₄ ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externCompatibility' T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = px ∷ externCompatibility T' T'CompatWithTs envTypesForSplit {Γ} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {Ts} {T} (envTypesConcatMatchNotFound {R = .Ts} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} .(Δ ,ₗ l ⦂ T₁) o origEnvTypes l₁NotInΔ') lInρ T₁Connected origCompat spl = let lNeql₁ = ≢-sym (∉dom-≢ l₁NotInΔ') lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ lNeql₁ compatibilityWithOrigρ = envTypesForSplit origEnvTypes lInRestOfρ T₁Connected origCompat spl envTypes = envTypesConcatMatchNotFound (Δ ,ₗ l ⦂ T₃) o (proj₁ (proj₂ compatibilityWithOrigρ)) (∉domPreservation l₁NotInΔ' ) in ⟨ proj₁ compatibilityWithOrigρ , ⟨ envTypes , proj₂ (proj₂ compatibilityWithOrigρ) ⟩ ⟩ envTypesForSplit {Γ} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {Ts} {T} (envTypesConcatMismatch {R = .Ts} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} .(Δ ,ₗ l ⦂ T₁) o o' oNeqo' origEnvTypes) lInρ T₁Connected origCompat spl = let oExprNeqo'Expr = λ objValsEq → (objValInjective oNeqo') (Eq.sym objValsEq) lInRestOfρ = IndirectRefContext.irrelevantReductionsInValuesOK lInρ oExprNeqo'Expr compatibilityWithOrigρ = envTypesForSplit origEnvTypes lInRestOfρ T₁Connected origCompat spl envTypes = envTypesConcatMismatch (Δ ,ₗ l ⦂ T₃) o o' oNeqo' (proj₁ (proj₂ compatibilityWithOrigρ)) in ⟨ proj₁ compatibilityWithOrigρ , ⟨ envTypes , proj₂ (proj₂ compatibilityWithOrigρ) ⟩ ⟩ envTypesForSplit {Γ} {.(re μ IndirectRefContext.∅ φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {.[]} {T} (envTypesEmpty {μ = μ} {φ = φ} {ψ = ψ} {Δ = .(Δ ,ₗ l ⦂ T₁)} {o = .o}) T₁InTs T₁Connected origCompat spl = ⟨ [] , ⟨ envTypesEmpty , ⟨ [] , ⟨ emptyTypeList refl , (λ T' → λ a → []) ⟩ ⟩ ⟩ ⟩ oExtensionIrrelevantToEnvTypes : ∀ {Σ Δ R o o' forbiddenRefs T} → EnvTypes Σ Δ o' forbiddenRefs R → EnvTypes Σ (Δ ,ₒ o ⦂ T) o' forbiddenRefs R oExtensionIrrelevantToEnvTypes {.(re μ (ρ IndirectRefContext., l ⦂ objVal o₁) φ ψ)} {Δ} {.(T₁ ∷ R)} {o} {.o₁} {forbiddenRefs} {T} (envTypesConcatMatchFound {R = R} {l = l} {T = T₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} Δ o₁ envTypes x x₁) = let recurse = oExtensionIrrelevantToEnvTypes envTypes in envTypesConcatMatchFound (Δ ,ₒ o ⦂ T) o₁ recurse x x₁ oExtensionIrrelevantToEnvTypes {.(re μ (ρ IndirectRefContext., l ⦂ objVal o₁) φ ψ)} {Δ} {R} {o} {.o₁} {forbiddenRefs} {T} (envTypesConcatMatchNotFound {R = .R} {l = l} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} Δ o₁ envTypes x) = let recurse = oExtensionIrrelevantToEnvTypes envTypes in envTypesConcatMatchNotFound (Δ ,ₒ o ⦂ T) o₁ recurse x oExtensionIrrelevantToEnvTypes {.(re μ (ρ IndirectRefContext., l ⦂ objVal o') φ ψ)} {Δ} {R} {o} {.o₁} {forbiddenRefs} {T} (envTypesConcatMismatch {R = .R} {l = l} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} Δ o₁ o' x envTypes) = let recurse = oExtensionIrrelevantToEnvTypes envTypes in envTypesConcatMismatch (Δ ,ₒ o ⦂ T) o₁ o' x recurse oExtensionIrrelevantToEnvTypes {.(re μ IndirectRefContext.∅ φ ψ)} {Δ} {.[]} {o} {o'} {forbiddenRefs} {T} (envTypesEmpty {μ = μ} {φ = φ} {ψ = ψ} {Δ = .Δ} {o = .o'} {forbiddenRefs = .forbiddenRefs}) = envTypesEmpty envTypesForSplitOMismatch : ∀ {Γ Σ Δ l o' T₁ T₂ T₃ Ts forbiddenRefs} → EnvTypes Σ (Δ ,ₗ l ⦂ T₁) o' forbiddenRefs Ts → IsConnectedTypeList Ts → Γ ⊢ T₁ ⇛ T₂ / T₃ → ∃[ Ts' ] ((EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o' forbiddenRefs Ts') × (IsConnectedTypeList Ts') × (∀ T' → All (λ T'' → T' ⟷ T'') Ts → All (λ T'' → T' ⟷ T'') Ts')) envTypesForSplitOMismatch {Γ} {Σ@.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {.o'} {T₁} {T₂} {T₃} {.(T ∷ R)} {forbiddenRefs} (envTypesConcatMatchFound {R = R} {l = l₁} {T = T} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T₁) o' origEnvTypes lookupResult l₁NotForbidden) (consTypeList firstConnected restConnected) spl with l₁ ≟ l ... | yes l₁Eql = -- We looked up l₁ in Δ' and got T₁. We're going to give T₃ now. ⟨ Ts' , ⟨ envTypesTs' , ⟨ (consTypeList T₃CompatWithRestOfEnvTypes restConnected) , externalCompat ⟩ ⟩ ⟩ where Ts' = T₃ ∷ R origEnvTypesWithL1 : EnvTypes (re μ ρ φ ψ) (Δ ,ₗ l₁ ⦂ T₁) o' (l₁ ∷ forbiddenRefs) R origEnvTypesWithL1 = Eq.subst (λ a → EnvTypes (re μ ρ φ ψ) (Δ ,ₗ a ⦂ T₁) o' (l₁ ∷ forbiddenRefs) R) (Eq.sym l₁Eql) origEnvTypes forbiddenOK = envTypesForbiddenRefsObserved {T' = T₃} Δ o' (here refl) origEnvTypesWithL1 forbiddenOKInL₁ : EnvTypes (re μ ρ φ ψ) (Δ ,ₗ l ⦂ T₃) o' (l₁ ∷ forbiddenRefs) R forbiddenOKInL₁ = Eq.subst (λ a → EnvTypes (re μ ρ φ ψ) (Δ ,ₗ a ⦂ T₃) o' (l₁ ∷ forbiddenRefs) R) l₁Eql forbiddenOK envTypesTs' : EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o' forbiddenRefs Ts' envTypesTs' = envTypesConcatMatchFound ((Δ ,ₗ l ⦂ T₃)) o' forbiddenOKInL₁ ( (Eq.subst (λ a → StaticEnv.locEnv Δ , a ⦂ T₃ ∋ l₁ ⦂ T₃) l₁Eql Z)) l₁NotForbidden lookupResultWithl : (StaticEnv.locEnv Δ , l ⦂ T₁) ∋ l ⦂ T lookupResultWithl = Eq.subst (λ a → StaticEnv.locEnv Δ , l ⦂ T₁ ∋ a ⦂ T) l₁Eql lookupResult TEqT₁ : T ≡ T₁ TEqT₁ = contextLookupUnique lookupResultWithl Z T₄CompatWithRestOfEnvTypes = firstConnected T₁CompatWithRestOfEnvTypes = Eq.subst (λ a → All (λ T' → a ⟷ T') R) TEqT₁ T₄CompatWithRestOfEnvTypes T₂CompatWithRestOfEnvTypes : All (λ T' → T₂ ⟷ T') R T₂CompatWithRestOfEnvTypes = t₁CompatibilityImpliest₂Compatibility T₁CompatWithRestOfEnvTypes spl T₂CompatWithT₃ = splitCompatibility spl -- Need to prove everything in R is connected to T₃, given that everything in R is connected to T₄ (≡ T₁). -- Follows from splittingRespectsHeap. T₃CompatWithRestOfEnvTypes : All (λ T' → T₃ ⟷ T') R T₃CompatWithRestOfEnvTypes = t₁CompatibilityImpliest₃Compatibility T₁CompatWithRestOfEnvTypes spl externalCompat : (T' : Type) → All (λ T'' → T' ⟷ T'') (T ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externalCompat T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = let T'CompatT₁ = Eq.subst (λ a → T' ⟷ a) TEqT₁ px T'CompatT₃ = proj₂ (splittingRespectsHeap spl T'CompatT₁) in T'CompatT₃ ∷ T'CompatWithTs ... | no l₁Neql with T ≟t T₁ ... | yes TEqT₁ = ⟨ Ts' , ⟨ envTypesTs' , ⟨ consTypeList TCompatWithR' (proj₁ (proj₂ (proj₂ R'WithProof))) , externCompatibility' ⟩ ⟩ ⟩ where -- Because we're in envTypeConcatMatchFound, l₁ ⦂ o was at the end of the context, and we found l₁ ⦂ T₄ in Δ , l ⦂ T₁. -- But l ≢ l₁, so we will be able to find l₁ ⦂ T₄ in Δ and use the same rule. -- However, there may be l's in ρ, which may result in a different R than before! Some T₁'s may be replaced with T₃'s. R'WithProof = envTypesForSplitOMismatch origEnvTypes restConnected spl R' = proj₁ R'WithProof Ts' = T ∷ R' l₁InΔ : ((StaticEnv.locEnv Δ) , l ⦂ T₃) ∋ l₁ ⦂ T l₁InΔ = irrelevantExtensionsOK {t = T} {t' = T₃} (irrelevantReductionsOK lookupResult l₁Neql) l₁Neql envTypesTs' = envTypesConcatMatchFound (Δ ,ₗ l ⦂ T₃) o' (proj₁ (proj₂ R'WithProof)) l₁InΔ l₁NotForbidden externCompatibility = proj₂ (proj₂ (proj₂ R'WithProof)) TCompatWithR' : All (λ T' → T ⟷ T') R' TCompatWithR' = externCompatibility T firstConnected externCompatibility' : (T' : Type) → All (λ T'' → T' ⟷ T'') (T ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externCompatibility' T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = px ∷ externCompatibility T' T'CompatWithTs ... | no TNeqT₁ = ⟨ Ts' , ⟨ envTypesTs' , ⟨ consTypeList T₄CompatWithR' (proj₁ (proj₂ (proj₂ R'WithProof))) , externCompatibility' ⟩ ⟩ ⟩ where -- Because we're in envTypeConcatMatchFound, l₁ ⦂ o was at the end of the context, and we found l₁ ⦂ T₄ in Δ , l ⦂ T₁. -- But l ≢ l₁, so we will be able to find l₁ ⦂ T₄ in Δ and use the same rule. -- However, there may be l's in ρ, which may result in a different R than before! Some T₁'s may be replaced with T₃'s. R'WithProof = envTypesForSplitOMismatch origEnvTypes restConnected spl R' = proj₁ R'WithProof Ts' = T ∷ R' l₁InΔ : ((StaticEnv.locEnv Δ) , l ⦂ T₃) ∋ l₁ ⦂ T l₁InΔ = irrelevantExtensionsOK {t = T} {t' = T₃} (irrelevantReductionsOK lookupResult l₁Neql) l₁Neql envTypesTs' = envTypesConcatMatchFound (Δ ,ₗ l ⦂ T₃) o' (proj₁ (proj₂ R'WithProof)) l₁InΔ l₁NotForbidden externCompatibility = proj₂ (proj₂ (proj₂ R'WithProof)) T₄CompatWithR' : All (λ T' → T ⟷ T') R' T₄CompatWithR' = externCompatibility T firstConnected externCompatibility' : (T' : Type) → All (λ T'' → T' ⟷ T'') (T ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externCompatibility' T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = px ∷ externCompatibility T' T'CompatWithTs envTypesForSplitOMismatch {Γ} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {.o'} {T₁} {T₂} {T₃} {Ts} {forbiddenRefs} (envTypesConcatMatchNotFound {R = .Ts} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T₁) o' origEnvTypes l₁NotInΔ') origCompat spl = let compatibilityWithOrigρ = envTypesForSplitOMismatch origEnvTypes origCompat spl envTypes = envTypesConcatMatchNotFound (Δ ,ₗ l ⦂ T₃) o' (proj₁ (proj₂ compatibilityWithOrigρ)) (∉domPreservation l₁NotInΔ' ) in ⟨ proj₁ compatibilityWithOrigρ , ⟨ envTypes , proj₂ (proj₂ compatibilityWithOrigρ) ⟩ ⟩ envTypesForSplitOMismatch {Γ} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {o''} {T₁} {T₂} {T₃} {Ts} {forbiddenRefs} (envTypesConcatMismatch {R = .Ts} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T₁) o'' o' o''Neqo' origEnvTypes) origCompat spl = -- We know l : o is in ρ, and we're looking for matches o'', but the last item doesn't match because o' ≢ o''. let compatibilityWithOrigρ = envTypesForSplitOMismatch origEnvTypes origCompat spl -- o'NeqO origCompat spl envTypes = envTypesConcatMismatch (Δ ,ₗ l ⦂ T₃) o'' o' o''Neqo' (proj₁ (proj₂ compatibilityWithOrigρ)) in ⟨ proj₁ compatibilityWithOrigρ , ⟨ envTypes , proj₂ (proj₂ compatibilityWithOrigρ) ⟩ ⟩ envTypesForSplitOMismatch {Γ} {.(re μ IndirectRefContext.∅ φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {.[]} {T} (envTypesEmpty {μ = μ} {φ = φ} {ψ = ψ} {Δ = .(Δ ,ₗ l ⦂ T₁)} {o = .o}) origCompat spl = ⟨ [] , ⟨ envTypesEmpty , ⟨ emptyTypeList refl , (λ T' → λ a → []) ⟩ ⟩ ⟩ iterateExternalCompat : ∀ {E E'} → {L : List Type} → (∀ T' → All (λ T'' → T' ⟷ T'') E → All (λ T'' → T' ⟷ T'') E') → All (λ T → All (λ T' → T ⟷ T') E) L → All (λ T → All (λ T' → T ⟷ T') E') L iterateExternalCompat {L = []} externalCompat allCompat = [] iterateExternalCompat {L = T ∷ rest} externalCompat (_∷_ {x = .T} {xs = .rest} TCompat restCompat) = (externalCompat T TCompat) ∷ (iterateExternalCompat {L = rest} externalCompat restCompat) -- Previously, all the types aliasing o were connected. Now, we've extended the context due to a split, and we need to show we still have connectivity. -- The idea here is that the expression in question is of type T₂, so the reference left in the heap is of type T₃. -- o corresponds to the bject that was affected by the split, whereas o' is the reference we are interested in analyzing aliases to. splitReplacementOK : ∀ {Γ Σ Δ o o' l} → {t₁ t₂ : Tc} → {T₁ T₂ T₃ : Type} → (T₁EqctT₁ : T₁ ≡ (contractType t₁)) → (T₂EqctT₂ : T₂ ≡ (contractType t₂)) → (globalConsistency : (Σ & (Δ ,ₗ l ⦂ T₁) ok)) → o ≡ proj₁ (locLookup {T = t₁} globalConsistency (Eq.subst (λ a → StaticEnv.locEnv (Δ ,ₗ l ⦂ T₁) ∋ l ⦂ a) T₁EqctT₁ (TypeEnvContext.Z {StaticEnv.locEnv Δ} {l} {T₁}) )) → (RT : RefTypes Σ (Δ ,ₗ l ⦂ T₁) o') → IsConnected Σ (Δ ,ₗ l ⦂ T₁) o' RT → Γ ⊢ T₁ ⇛ T₂ / T₃ → ∃[ RT' ] (IsConnected Σ ((Δ ,ₗ l ⦂ T₃) ,ₒ o ⦂ T₂) o' RT') splitReplacementOK {Γ} {Σ} {Δ} {o} {o'} {l} {t₁} {t₂} {T₁} {T₂} {T₃} refl refl origConsis@(ok _ _ _ objLookup refConsistencyFunc) refl RT rConnected@(isConnected _ oTypesListConnected oConnectedToFieldTypes oConnectedToLTypes envFieldConnected@(envTypesConnected _ etc fieldTypesConnected fieldEnvTypesConnected)) spl with (o' ≟ o) ... | yes osEq = -- In this case, there are no O types yet, but adding o ⦂ T₂ will add one. ⟨ RT' , isConnected RT' TsForOsConnected TsForOsConnectedToFieldTypes TsForOsConnectedToLTypes envAndFieldConnected ⟩ where Δ' = ((Δ ,ₗ l ⦂ T₃) ,ₒ o ⦂ T₂) TsForOs = [ T₂ ] -- Since o ≡ o', when we look up o' in the new context, we'll get T₂. o'TypeExtension : [ T₂ ] ≡ ctxTypes (StaticEnv.objEnv Δ Context., o' ⦂ T₂) o' o'TypeExtension = ctxTypesExtension {StaticEnv.objEnv (Δ ,ₗ l ⦂ T₃)} {o'} {T₂} RT'o'TypesEq : [ T₂ ] ≡ ctxTypes (StaticEnv.objEnv Δ') o' RT'o'TypesEq = Eq.subst (λ a → ([ T₂ ] ≡ (ctxTypes (StaticEnv.objEnv Δ , a ⦂ T₂) o'))) (osEq) o'TypeExtension lLookupResult = objLookup l t₁ Z oForL = proj₁ lLookupResult lInρ = proj₁ (proj₂ lLookupResult) -- Can I show that T₂ is compatible with all of the old env types? Because that's really what I need. lInρForFindLocation = (Eq.subst (λ a → RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal a) (Eq.sym osEq) lInρ) TInEnvTypes = findLocationInEnvTypes (RefTypes.envTypesList RT) (RefTypes.envTypes RT) etc lInρForFindLocation newEnvTypes = envTypesForSplit (RefTypes.envTypes RT) lInρForFindLocation (proj₂ TInEnvTypes) etc spl RT' : RefTypes Σ Δ' o' RT' = record {oTypesList = TsForOs ; oTypes = Eq.sym (RT'o'TypesEq) ; envTypesList = proj₁ newEnvTypes ; envTypes = oExtensionIrrelevantToEnvTypes (proj₁ (proj₂ newEnvTypes)) ; fieldTypesList = RefTypes.fieldTypesList RT} -- field types are unchanged. TsForOsIsRight : TsForOs ≡ (RefTypes.oTypesList RT') TsForOsIsRight = Eq.trans RT'o'TypesEq (RefTypes.oTypes RT') TsForOsConnected : IsConnectedTypeList (RefTypes.oTypesList RT') TsForOsConnected = (Eq.subst (λ a → IsConnectedTypeList a) TsForOsIsRight (singleElementListsAreConnected T₂)) -- Need to find the proof that T₁ is compatible with all the field types and use it directly. It has to be in there somewhere. -- Specifically, it has to be in envFieldConnected because T₁ has to have been in the old env types. oldEnvFieldsCompatible : All (λ T → All (_⟷_ T) (RefTypes.fieldTypesList RT)) (RefTypes.envTypesList RT) oldEnvFieldsCompatible = envFieldInversion3 envFieldConnected -- One of the items in oldEnvFieldsCompatible is proof that T₁ is connected to everything in fieldTypesList! But which one? T₁CompatWithAllFieldTypes : All (λ T' → T₁ ⟷ T') (RefTypes.fieldTypesList RT) T₁CompatWithAllFieldTypes = prevCompatibilityImpliesCompatibility RT (RefTypes.fieldTypesList RT) oldEnvFieldsCompatible etc (Eq.subst (λ a → RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal a) (Eq.sym osEq) lInρ) T₂CompatWithAllFieldTypes = t₁CompatibilityImpliest₂Compatibility T₁CompatWithAllFieldTypes spl TsForOsConnectedToFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.fieldTypesList RT')) (RefTypes.oTypesList RT') TsForOsConnectedToFieldTypes = T₂CompatWithAllFieldTypes ∷ [] T₂ConnectedToLTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) [ T₂ ] T₂ConnectedToLTypes = proj₁ (proj₂ (proj₂ newEnvTypes)) ∷ [] TsForOsConnectedToLTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.oTypesList RT') TsForOsConnectedToLTypes = Eq.subst (λ a → All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) a) TsForOsIsRight T₂ConnectedToLTypes externalCompat : ∀ T' → All (λ T'' → T' ⟷ T'') (RefTypes.envTypesList RT) → All (λ T'' → T' ⟷ T'') (RefTypes.envTypesList RT') externalCompat = proj₂ (proj₂ (proj₂ (proj₂ newEnvTypes))) insideOutEnvTypesFieldTypesCompat : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT)) (RefTypes.fieldTypesList RT) insideOutEnvTypesFieldTypesCompat = allInsideOut splitSymmetric fieldEnvTypesConnected -- turn prev. inside out newEnvTypesCompatWithFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.fieldTypesList RT) newEnvTypesCompatWithFieldTypes = iterateExternalCompat {L = RefTypes.fieldTypesList RT} externalCompat insideOutEnvTypesFieldTypesCompat newEnvTypesCompatWithNewFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.fieldTypesList RT') newEnvTypesCompatWithNewFieldTypes = newEnvTypesCompatWithFieldTypes -- b/c old field types ≡ new field types envTypesCompatibleWithFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.fieldTypesList RT')) (RefTypes.envTypesList RT') envTypesCompatibleWithFieldTypes = allInsideOut splitSymmetric newEnvTypesCompatWithNewFieldTypes -- turn prev. inside out envAndFieldConnected : IsConnectedEnvAndField Σ ((Δ ,ₗ l ⦂ T₃) ,ₒ o ⦂ T₂) o' RT' envAndFieldConnected = envTypesConnected RT' ( proj₁ (proj₂ (proj₂ (proj₂ newEnvTypes)))) fieldTypesConnected envTypesCompatibleWithFieldTypes ... | no osNeq = -- The change in Δ has no impact on looking up o', since o' ≢ o. let lLookupResult = objLookup l t₁ Z oForL = proj₁ lLookupResult lInρ = proj₁ (proj₂ lLookupResult) Δ' = ((Δ ,ₗ l ⦂ T₃) ,ₒ o ⦂ T₂) oTypesUnchanged : ctxTypes (StaticEnv.objEnv Δ') o' ≡ ctxTypes (StaticEnv.objEnv (Δ ,ₗ l ⦂ T₃)) o' oTypesUnchanged = ctxTypesExtensionNeq osNeq newEnvTypes = envTypesForSplitOMismatch (RefTypes.envTypes RT) etc spl RT' = record { oTypesList = RefTypes.oTypesList RT ; oTypes = Eq.trans oTypesUnchanged (RefTypes.oTypes RT) ; envTypesList = proj₁ newEnvTypes ; envTypes = oExtensionIrrelevantToEnvTypes (proj₁ (proj₂ newEnvTypes)) ; fieldTypesList = RefTypes.fieldTypesList RT } externalCompat = proj₂ (proj₂ (proj₂ newEnvTypes)) TsForOsConnectedToLTypes = iterateExternalCompat externalCompat oConnectedToLTypes insideOutEnvTypesFieldTypesCompat : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT)) (RefTypes.fieldTypesList RT) insideOutEnvTypesFieldTypesCompat = allInsideOut splitSymmetric fieldEnvTypesConnected -- turn prev. inside out newEnvTypesCompatWithFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.fieldTypesList RT) newEnvTypesCompatWithFieldTypes = iterateExternalCompat {L = RefTypes.fieldTypesList RT} externalCompat insideOutEnvTypesFieldTypesCompat newEnvTypesCompatWithNewFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.fieldTypesList RT') newEnvTypesCompatWithNewFieldTypes = newEnvTypesCompatWithFieldTypes -- b/c old field types ≡ new field types envTypesCompatibleWithFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.fieldTypesList RT')) (RefTypes.envTypesList RT') envTypesCompatibleWithFieldTypes = allInsideOut splitSymmetric newEnvTypesCompatWithNewFieldTypes -- turn prev. inside out envAndFieldConnected = envTypesConnected RT' ( proj₁ (proj₂ (proj₂ newEnvTypes))) fieldTypesConnected envTypesCompatibleWithFieldTypes in ⟨ RT' , isConnected RT' oTypesListConnected oConnectedToFieldTypes TsForOsConnectedToLTypes envAndFieldConnected ⟩ ",16258,True,3544.6750899427557,median "open import Data.Bool hiding (if_then_else_) open import Data.Empty open import Data.List open import Data.List.Properties open import Data.Maybe open import Data.Product open import Data.Sum open import Data.Unit open import Relation.Binary.PropositionalEquality hiding (Extensionality ; [_]) open import Relation.Nullary open import Relation.Nullary.Negation module EffectAnnotations where open import Axiom.Extensionality.Propositional open import Axiom.UniquenessOfIdentityProofs -- ASSUMING FUNCTION EXTENSIONALITY postulate fun-ext : ∀ {a b} → Extensionality a b ifun-ext : ∀ {a b} → ExtensionalityImplicit a b -- SIGNAL AND INTERRUPT NAMES postulate Σₛ : Set -- SIGNAL AND INTERRUPT NAMES HAVE DECIDABLE EQUALITY postulate decₛ : (op op' : Σₛ) → Dec (op ≡ op') if_≡_then_else_ : {A : Set} → Σₛ → Σₛ → A → A → A if op ≡ op' then x else y with decₛ op op' ... | yes p = x ... | no ¬p = y ite-≡ : {A : Set} {op : Σₛ} {x y : A} → ----------------------------- if op ≡ op then x else y ≡ x ite-≡ {A} {op} with decₛ op op ite-≡ {A} {op} | yes p = refl ite-≡ {A} {op} | no ¬p = ⊥-elim (¬p refl) ite-≢ : {A : Set} {op op' : Σₛ} {x y : A} → op ≢ op' → ------------------------------ if op ≡ op' then x else y ≡ y ite-≢ {A} {op} {op'} p with decₛ op op' ite-≢ {A} {op} {op'} p | yes q = ⊥-elim (p q) ite-≢ {A} {op} {op'} p | no ¬q = refl -- EFFECT ANNOTATIONS FOR OUTGOING SIGNALS (O) AND INTERRUPT HANDLERS (I) data O : Set where omap : (Σₛ → Maybe ⊤) → O data I : Set where imap : (Σₛ → Maybe (O × I)) → I -- EMPTY EFFECT ANNOTATIONS ∅ₒ : O ∅ₒ = omap (λ _ → nothing) ∅ᵢ : I ∅ᵢ = imap (λ _ → nothing) -- UNION OF EFFECT ANNOTATIONS ∪ₒ-aux' : (o o' : Maybe ⊤) → Maybe ⊤ ∪ₒ-aux' nothing o' = o' ∪ₒ-aux' (just tt) o' = just tt ∪ₒ-aux : (o o' : Σₛ → Maybe ⊤) → Σₛ → Maybe ⊤ ∪ₒ-aux o o' op = ∪ₒ-aux' (o op) (o' op) _∪ₒ_ : O → O → O (omap o) ∪ₒ (omap o') = omap (∪ₒ-aux o o') mutual ∪ᵢ-aux : (i i' : Σₛ → Maybe (O × I)) → Σₛ → Maybe (O × I) ∪ᵢ-aux i i' op = ∪ᵢ-aux' (i op) (i' op) ∪ᵢ-aux' : (oi oi' : Maybe (O × I)) → Maybe (O × I) ∪ᵢ-aux' nothing oi' = oi' ∪ᵢ-aux' (just oi'') nothing = just oi'' ∪ᵢ-aux' (just (o'' , (imap i''))) (just (o''' , (imap i'''))) = just (o'' ∪ₒ o''' , imap (∪ᵢ-aux i'' i''')) _∪ᵢ_ : I → I → I (imap i) ∪ᵢ (imap i') = imap (∪ᵢ-aux i i') -- SETTING THE VALUE OF EFFECT ANNOTATION AT A SPECIFIC INTERRUPT NAME _[_↦_]ᵢ : I → Σₛ → Maybe (O × I) → I (imap i) [ op ↦ v ]ᵢ = imap (λ op' → if op ≡ op' then v else i op') -- ACTION OF INTERRUPTS ON EFFECT ANNOTATIONS infix 40 _↓ₑ_ ↓ₑ-auxₒ : Σₛ → Maybe (O × I) → O → O ↓ₑ-auxₒ op nothing o = o ↓ₑ-auxₒ op (just (o' , i')) o = o ∪ₒ o' ↓ₑ-auxᵢ : Σₛ → Maybe (O × I) → I → I ↓ₑ-auxᵢ op nothing i = i ↓ₑ-auxᵢ op (just (o' , i')) i = (i [ op ↦ nothing ]ᵢ) ∪ᵢ i' _↓ₑ_ : Σₛ → O × I → O × I op ↓ₑ (omap o , imap i) = (↓ₑ-auxₒ op (i op) (omap o) , ↓ₑ-auxᵢ op (i op) (imap i)) -- GENERALISED ACTION OF INTERRUPTS ON EFFECT ANNOTATIONS _↓↓ₑ_ : List Σₛ → O × I → O × I [] ↓↓ₑ (o , i) = (o , i) (op ∷ ops) ↓↓ₑ (o , i) = op ↓ₑ (ops ↓↓ₑ (o , i)) ↓↓ₑ-act : {o : O} {i : I} → (ops ops' : List Σₛ) → ------------------------------------------------------ (ops ++ ops') ↓↓ₑ (o , i) ≡ ops ↓↓ₑ (ops' ↓↓ₑ (o , i)) ↓↓ₑ-act [] ops' = refl ↓↓ₑ-act (op ∷ ops) ops' = cong (λ oi → op ↓ₑ oi) (↓↓ₑ-act ops ops') -- CHECKING THE CONTENTS OF EFFECT ANNOTATIONS _∈ₒ_ : Σₛ → O → Set op ∈ₒ (omap o) = o op ≡ just tt lkpᵢ : Σₛ → I → Maybe (O × I) lkpᵢ op (imap i) = i op -- SUBTYPING RELATIONS FOR EFFECT ANNOTATIONS _⊑ₒ_ : O → O → Set o ⊑ₒ o' = (op : Σₛ) → op ∈ₒ o → op ∈ₒ o' data _⊑ᵢ_ (i i' : I) : Set where rel : ((op : Σₛ) → {o : O} → {i'' : I} → lkpᵢ op i ≡ just (o , i'') → Σ[ o' ∈ O ] Σ[ i''' ∈ I ] (lkpᵢ op i' ≡ just (o' , i''') × o ⊑ₒ o' × i'' ⊑ᵢ i''')) → i ⊑ᵢ i' -- PRODUCT ORDER SUBTYPING RELATION _⊑_ : O × I → Maybe (O × I) → Set x ⊑ nothing = ⊥ (o , i) ⊑ just (o' , i') = (o ⊑ₒ o') × (i ⊑ᵢ i') ⊑-just : {o : O} {i : I} {oi : Maybe (O × I)} → (o , i) ⊑ oi → --------------------------------------------- Σ[ o' ∈ O ] Σ[ i' ∈ I ] (oi ≡ just (o' , i')) ⊑-just {oi = just (o' , i')} p = o' , i' , refl ⊑-proj : {o o' : O} {i i' : I} {oi : Maybe (O × I)} → (o , i) ⊑ oi → oi ≡ just (o' , i') → -------------------------------------------- o ⊑ₒ o' × i ⊑ᵢ i' ⊑-proj {oi = just (o'' , i'')} p refl = p -- SUBTYPING RELATIONS ARE PREORDERS ⊑ₒ-refl : {o : O} → --------- o ⊑ₒ o ⊑ₒ-refl = λ op p → p ⊑ₒ-trans : {o o' o'' : O} → o ⊑ₒ o' → o' ⊑ₒ o'' → ---------------- o ⊑ₒ o'' ⊑ₒ-trans p q = λ op r → q op (p op r) ⊑ᵢ-refl : {i : I} → --------- i ⊑ᵢ i ⊑ᵢ-refl {imap i} = rel (λ op {o'} → λ { {imap i'} → λ p → ⊑ᵢ-refl-aux (i op) p }) where ⊑ᵢ-refl-aux : (oi : Maybe (O × I)) → ---------------------------------------------------------------------------------- {o' : O} {i' : Σₛ → Maybe (O × I)} → oi ≡ just (o' , imap i') → Σ[ o'' ∈ O ] Σ[ i'' ∈ I ] (oi ≡ just (o'' , i'') × (o' ⊑ₒ o'') × (imap i' ⊑ᵢ i'')) ⊑ᵢ-refl-aux (just .(o' , imap i')) {o'} {i'} refl = o' , (imap i' , (refl , (⊑ₒ-refl , ⊑ᵢ-refl {imap i'}))) ⊑ᵢ-trans : {i i' i'' : I} → i ⊑ᵢ i' → i' ⊑ᵢ i'' → ----------------- i ⊑ᵢ i'' ⊑ᵢ-trans {i} {i'} {i''} (rel p) (rel q) = rel (λ op {o} {j} r → ⊑ᵢ-trans-aux o j op (p op r)) where ⊑ᵢ-trans-aux' : (o : O) → (j : I) → (op : Σₛ) → (o' : O) → (j' : I) → lkpᵢ op i' ≡ just (o' , j') → (o ⊑ₒ o') → (j ⊑ᵢ j') → Σ[ o'' ∈ O ] Σ[ j'' ∈ I ] (lkpᵢ op i'' ≡ just (o'' , j'') × (o' ⊑ₒ o'') × (j' ⊑ᵢ j'')) → Σ[ o'' ∈ O ] Σ[ j'' ∈ I ] (lkpᵢ op i'' ≡ just (o'' , j'') × (o ⊑ₒ o'') × (j ⊑ᵢ j'')) ⊑ᵢ-trans-aux' o j op o' j' r' s t (o'' , j'' , r'' , s' , t') = o'' , j'' , r'' , ⊑ₒ-trans s s' , ⊑ᵢ-trans t t' ⊑ᵢ-trans-aux : (o : O) → (j : I) → (op : Σₛ) → Σ[ o' ∈ O ] Σ[ j' ∈ I ] (lkpᵢ op i' ≡ just (o' , j') × (o ⊑ₒ o') × (j ⊑ᵢ j')) → Σ[ o'' ∈ O ] Σ[ j'' ∈ I ] (lkpᵢ op i'' ≡ just (o'' , j'') × (o ⊑ₒ o'') × (j ⊑ᵢ j'')) ⊑ᵢ-trans-aux o j op (o' , j' , r' , s , t) = ⊑ᵢ-trans-aux' o j op o' j' r' s t (q op r') ⊑-refl : {o : O} {i : I} → ---------------------- (o , i) ⊑ just (o , i) ⊑-refl = (⊑ₒ-refl , ⊑ᵢ-refl) ⊑-trans : {oi : O × I} {oi' : Maybe (O × I)} {oi'' : O × I} {oi''' : Maybe (O × I)} → oi ⊑ oi' → oi' ≡ just oi'' → oi'' ⊑ oi''' → ------------------------------ oi ⊑ oi''' ⊑-trans {(o , i)} {_} {(o'' , i'')} {just (o''' , i''')} (pₒ , pᵢ) refl (rₒ , rᵢ) = (⊑ₒ-trans pₒ rₒ , ⊑ᵢ-trans pᵢ rᵢ) -- SUBTYPING RELATIONS ARE PROOF-IRRELEVANT ≡-uip : {X : Set} {x x' : X} → (p q : x ≡ x') → ---------------- p ≡ q ≡-uip refl refl = refl ⊑ₒ-irrelevant : {o o' : O} (p q : o ⊑ₒ o') → ----------------- p ≡ q ⊑ₒ-irrelevant {omap o} {omap o'} p q = fun-ext (λ op → fun-ext (λ r → ⊑ₒ-irrelevant-aux r)) where ⊑ₒ-irrelevant-aux : {op : Σₛ} → (r : op ∈ₒ (omap o)) → ---------------------- p op r ≡ q op r ⊑ₒ-irrelevant-aux {op} r with p op r | q op r ... | s | t = ≡-uip s t ⊑ᵢ-irrelevant : {i i' : I} (p q : i ⊑ᵢ i') → ----------------- p ≡ q ⊑ᵢ-irrelevant {imap i} {imap i'} (rel p) (rel q) = cong (λ r → rel r) (fun-ext (λ op → ifun-ext (λ {o''} → ifun-ext (λ {i''} → fun-ext (λ r → ⊑ᵢ-irrelevant-aux r))))) where ⊑ᵢ-irrelevant-aux : {op : Σₛ} {o'' : O} {i'' : I} → (r : i op ≡ just (o'' , i'')) → ------------------------------- p op r ≡ q op r ⊑ᵢ-irrelevant-aux {op} r with p op r | q op r ... | o''' , i''' , s , s' , s'' | o'''' , i'''' , t , t' , t'' with trans (sym s) t ... | refl with ⊑ₒ-irrelevant s' t' ... | refl with ⊑ᵢ-irrelevant s'' t'' ... | refl with ≡-uip s t ... | refl = refl -- LEFT UNIT FOR UNIONS OF EFFECT ANNOTATIONS ∪ₒ-lunit : (o : O) → ----------- ∅ₒ ∪ₒ o ≡ o ∪ₒ-lunit (omap o) = cong omap (fun-ext ∪ₒ-lunit-aux) where ∪ₒ-lunit-aux : (op : Σₛ) → ---------------------------------- ∪ₒ-aux (λ _ → nothing) o op ≡ o op ∪ₒ-lunit-aux op with o op ... | nothing = refl ... | just _ = refl ∪ᵢ-lunit : (i : I) → ----------- ∅ᵢ ∪ᵢ i ≡ i ∪ᵢ-lunit (imap i) = cong imap (fun-ext ∪ᵢ-lunit-aux) where ∪ᵢ-lunit-aux : (op : Σₛ) → ---------------------------------- ∪ᵢ-aux (λ _ → nothing) i op ≡ i op ∪ᵢ-lunit-aux op with i op ... | nothing = refl ... | just _ = refl -- LEFT AND RIGHT INCLUSIONS INTO UNIONS OF EFFECT ANNOTATIONS ∪ₒ-inl : {o o' : O} → ------------- o ⊑ₒ (o ∪ₒ o') ∪ₒ-inl {omap o} {omap o'} op with o op | o' op ... | nothing | nothing = λ p → p ... | nothing | just tt = λ _ → refl ... | just tt | nothing = λ p → p ... | just tt | just tt = λ p → p ∪ₒ-inr : {o o' : O} → ------------- o' ⊑ₒ (o ∪ₒ o') ∪ₒ-inr {omap o} {omap o'} op with o op | o' op ... | nothing | nothing = λ p → p ... | nothing | just tt = λ p → p ... | just tt | nothing = λ _ → refl ... | just tt | just tt = λ p → p ∪ᵢ-inl : {i i' : I} → ------------- i ⊑ᵢ (i ∪ᵢ i') ∪ᵢ-inl {imap i} {imap i'} = rel (λ op → ∪ᵢ-inl-aux (i op) (i' op)) where ∪ᵢ-inl-aux : (oi oi' : Maybe (O × I)) → {o : O} {i'' : I} → oi ≡ just (o , i'') → Σ[ o' ∈ O ] Σ[ i''' ∈ I ] (∪ᵢ-aux' oi oi' ≡ just (o' , i''') × (o ⊑ₒ o') × (i'' ⊑ᵢ i''')) ∪ᵢ-inl-aux (just .(o , i'')) nothing {o} {i''} refl = o , i'' , refl , ⊑ₒ-refl , ⊑ᵢ-refl ∪ᵢ-inl-aux (just .(o , imap i'')) (just (o' , imap i''')) {o} {imap i''} refl = o ∪ₒ o' , imap (∪ᵢ-aux i'' i''') , refl , ∪ₒ-inl , ∪ᵢ-inl ∪ᵢ-inr : {i i' : I} → ------------- i' ⊑ᵢ (i ∪ᵢ i') ∪ᵢ-inr {imap i} {imap i'} = rel (λ op → ∪ᵢ-inr-aux (i op) (i' op)) where ∪ᵢ-inr-aux : (oi oi' : Maybe (O × I)) → {o : O} {i'' : I} → oi' ≡ just (o , i'') → Σ[ o' ∈ O ] Σ[ i''' ∈ I ] (∪ᵢ-aux' oi oi' ≡ just (o' , i''') × (o ⊑ₒ o') × (i'' ⊑ᵢ i''')) ∪ᵢ-inr-aux nothing (just .(o , i'')) {o} {i''} refl = o , i'' , refl , ⊑ₒ-refl , ⊑ᵢ-refl ∪ᵢ-inr-aux (just (o' , imap i''')) (just .(o , imap i'')) {o} {imap i''} refl = o' ∪ₒ o , imap (∪ᵢ-aux i''' i'') , refl , ∪ₒ-inr , ∪ᵢ-inr -- COPAIRING FOR UNIONS OF EFFECT ANNOTATIONS ∪ₒ-copair : {o o' o'' : O} → o ⊑ₒ o'' → o' ⊑ₒ o'' → ---------------- (o ∪ₒ o') ⊑ₒ o'' ∪ₒ-copair {omap o} {omap o'} {omap o''} p q op = ∪ₒ-copair-aux (p op) (q op) where ∪ₒ-copair-aux : (p : op ∈ₒ (omap o) → op ∈ₒ (omap o'')) → (q : op ∈ₒ (omap o') → op ∈ₒ (omap o'')) → --------------------------------------------- op ∈ₒ (omap (∪ₒ-aux o o')) → op ∈ₒ (omap o'') ∪ₒ-copair-aux p q with o op | o' op ... | nothing | nothing = q ... | nothing | just tt = q ... | just tt | nothing = p ... | just tt | just tt = p inj-just : {X : Set} {x x' : X} → just x ≡ just x' → x ≡ x' inj-just refl = refl inj-pair₁ : {X Y : Set} {x x' : X} {y y' : Y} → (x , y) ≡ (x' , y') → x ≡ x' inj-pair₁ refl = refl inj-pair₂ : {X Y : Set} {x x' : X} {y y' : Y} → (x , y) ≡ (x' , y') → y ≡ y' inj-pair₂ refl = refl ∪ᵢ-copair : {i i' i'' : I} → i ⊑ᵢ i'' → i' ⊑ᵢ i'' → ---------------- (i ∪ᵢ i') ⊑ᵢ i'' ∪ᵢ-copair {imap i} {imap i'} {imap i''} (rel p) (rel q) = rel (λ op {o'''} {i'''} r → ∪ᵢ-copair-aux op o''' i''' (i op) (i' op) (i'' op) refl refl refl r) where ∪ᵢ-copair-aux : (op : Σₛ) → (o''' : O) → (i''' : I) (oi oi' oi'' : Maybe (O × I)) → (oi ≡ i op) → (oi' ≡ i' op) → (oi'' ≡ i'' op) → (r : ∪ᵢ-aux' oi oi' ≡ just (o''' , i''')) → Σ[ o' ∈ O ] Σ[ i'''' ∈ I ] (oi'' ≡ just (o' , i'''') × (o''' ⊑ₒ o') × (i''' ⊑ᵢ i'''')) ∪ᵢ-copair-aux op o''' i''' nothing (just oi') nothing r s t u with trans t (proj₁ (proj₂ (proj₂ (q op (trans (sym s) u))))) ... | () ∪ᵢ-copair-aux op o''' i''' nothing (just oi') (just oi'') r s t u = proj₁ (q op (trans (sym s) u)) , proj₁ (proj₂ (q op (trans (sym s) u))) , trans t (proj₁ (proj₂ (proj₂ (q op (trans (sym s) u))))) , proj₁ (proj₂ (proj₂ (proj₂ (q op (trans (sym s) u))))) , proj₂ (proj₂ (proj₂ (proj₂ (q op (trans (sym s) u))))) ∪ᵢ-copair-aux op o''' i''' (just oi) nothing oi'' r s t u = proj₁ (p op (trans (sym r) u)) , proj₁ (proj₂ (p op (trans (sym r) u))) , trans t (proj₁ (proj₂ (proj₂ (p op (trans (sym r) u))))) , proj₁ (proj₂ (proj₂ (proj₂ (p op (trans (sym r) u))))) , proj₂ (proj₂ (proj₂ (proj₂ (p op (trans (sym r) u))))) ∪ᵢ-copair-aux op o''' i''' (just (omap o'''' , imap i'''')) (just (omap o''''' , imap i''''')) nothing r s t u with trans t (proj₁ (proj₂ (proj₂ (p op (sym r))))) ... | () ∪ᵢ-copair-aux op o''' i''' (just (omap o'''' , imap i'''')) (just (omap o''''' , imap i''''')) (just (omap o'''''' , imap i'''''')) r s t u = omap o'''''' , imap i'''''' , refl , subst (λ o → o ⊑ₒ omap o'''''') (inj-pair₁ (inj-just u)) (∪ₒ-copair (subst (λ o → omap o'''' ⊑ₒ o) (inj-pair₁ (inj-just (sym (trans t (proj₁ (proj₂ (proj₂ (p op (sym r))))))))) (proj₁ (proj₂ (proj₂ (proj₂ (p op (sym r))))))) (subst (λ o → omap o''''' ⊑ₒ o) (inj-pair₁ (inj-just (sym (trans t (proj₁ (proj₂ (proj₂ (q op (sym s))))))))) (proj₁ (proj₂ (proj₂ (proj₂ (q op (sym s)))))))) , subst (λ i → i ⊑ᵢ imap i'''''') (inj-pair₂ (inj-just u)) (∪ᵢ-copair (subst (λ i → imap i'''' ⊑ᵢ i) (inj-pair₂ (inj-just (sym (trans t (proj₁ (proj₂ (proj₂ (p op (sym r))))))))) (proj₂ (proj₂ (proj₂ (proj₂ (p op (sym r))))))) (subst (λ i → imap i''''' ⊑ᵢ i) (inj-pair₂ (inj-just (sym (trans t (proj₁ (proj₂ (proj₂ (q op (sym s))))))))) (proj₂ (proj₂ (proj₂ (proj₂ (q op (sym s)))))))) -- FUNCTORIALITY OF UNIONS OF EFFECT ANNOTATIONS ∪ₒ-fun : {o o' o'' o''' : O} → o ⊑ₒ o'' → o' ⊑ₒ o''' → -------------------------- (o ∪ₒ o') ⊑ₒ (o'' ∪ₒ o''') ∪ₒ-fun p q = ∪ₒ-copair (⊑ₒ-trans p ∪ₒ-inl) (⊑ₒ-trans q ∪ₒ-inr) ∪ᵢ-fun : {i i' i'' i''' : I} → i ⊑ᵢ i'' → i' ⊑ᵢ i''' → -------------------------- (i ∪ᵢ i') ⊑ᵢ (i'' ∪ᵢ i''') ∪ᵢ-fun p q = ∪ᵢ-copair (⊑ᵢ-trans p ∪ᵢ-inl) (⊑ᵢ-trans q ∪ᵢ-inr) -- UNIONS OF INTERRUPT ANNOTATIONS ARE GIVEN BY POINTWISE UNIONS ∪ᵢ-∪ₒ : {op : Σₛ} {o'' o''' o'''' : O} {i i' i'' i''' i'''' : I} → lkpᵢ op (i ∪ᵢ i') ≡ just (o'' , i'') → lkpᵢ op i ≡ just (o''' , i''') → lkpᵢ op i' ≡ just (o'''' , i'''') → --------------------------------------- o'' ≡ o''' ∪ₒ o'''' ∪ᵢ-∪ₒ {op} {o''} {o'''} {o''''} {imap i} {imap i'} p q r with i op | i' op ∪ᵢ-∪ₒ {op} {.(o''' ∪ₒ o'''')} {o'''} {o''''} {imap i} {imap i'} {_} {imap i'''} {imap i''''} refl refl refl | just .(o''' , imap i''') | just .(o'''' , imap i'''') = refl ∪ᵢ-∪ᵢ : {op : Σₛ} {o'' o''' o'''' : O} {i i' i'' i''' i'''' : I} → lkpᵢ op (i ∪ᵢ i') ≡ just (o'' , i'') → lkpᵢ op i ≡ just (o''' , i''') → lkpᵢ op i' ≡ just (o'''' , i'''') → --------------------------------------- i'' ≡ i''' ∪ᵢ i'''' ∪ᵢ-∪ᵢ {op} {o''} {o'''} {o''''} {imap i} {imap i'} p q r with i op | i' op ∪ᵢ-∪ᵢ {op} {.(o''' ∪ₒ o'''')} {o'''} {o''''} {imap i} {imap i'} {_} {imap i'''} {imap i''''} refl refl refl | just .(o''' , imap i''') | just .(o'''' , imap i'''') = refl -- INCLUSION INTO ACTED UPON EFFECT ANNOTATION ↓ₑ-⊑ₒ : {o : O} {i : I} {op : Σₛ} → -------------------------- o ⊑ₒ proj₁ (op ↓ₑ (o , i)) ↓ₑ-⊑ₒ {omap o} {imap i} {op} op' p with i (op) ... | nothing = p ... | just (o' , i') = ∪ₒ-inl op' p ↓ₑ-⊑ₒ-o' : {o o' : O} {i i' : I} {op : Σₛ} → lkpᵢ op i ≡ just (o' , i') → --------------------------- o' ⊑ₒ proj₁ (op ↓ₑ (o , i)) ↓ₑ-⊑ₒ-o' {omap o} {omap o'} {imap i} {imap i'} {op} p with i (op) ↓ₑ-⊑ₒ-o' {omap o} {omap o'} {imap i} {imap i'} {op} refl | just .(omap o' , imap i') = ↓ₑ-⊑ₒ-o'-aux where ↓ₑ-⊑ₒ-o'-aux : (op' : Σₛ) → o' op' ≡ just tt → ∪ₒ-aux o o' op' ≡ just tt ↓ₑ-⊑ₒ-o'-aux op' p with o op' ↓ₑ-⊑ₒ-o'-aux op' p | nothing = p ↓ₑ-⊑ₒ-o'-aux op' p | just tt = refl ↓ₑ-⊑ₒ-i' : {o o' : O} {i i' : I} {op : Σₛ} → lkpᵢ op i ≡ just (o' , i') → --------------------------- i' ⊑ᵢ proj₂ (op ↓ₑ (o , i)) ↓ₑ-⊑ₒ-i' {omap o} {omap o'} {imap i} {imap i'} {op} p with i (op) ↓ₑ-⊑ₒ-i' {omap o} {omap o'} {imap i} {imap i'} {op} refl | just .(omap o' , imap i') = rel ↓ₑ-⊑ₒ-i'-aux where ↓ₑ-⊑ₒ-i'-aux : (op' : Σₛ) {o'' : O} {i'' : I} → i' op' ≡ just (o'' , i'') → Σ[ o''' ∈ O ] Σ[ i''' ∈ I ] (∪ᵢ-aux (λ op' → if op ≡ op' then nothing else i op') i' op' ≡ just (o''' , i''') × (o'' ⊑ₒ o''') × (i'' ⊑ᵢ i''')) ↓ₑ-⊑ₒ-i'-aux op' {o''} {i''} p with decₛ op op' ↓ₑ-⊑ₒ-i'-aux op' {o''} {i''} p | yes refl with i' (op) ↓ₑ-⊑ₒ-i'-aux op' {o''} {i''} refl | yes refl | just .(o'' , i'') = o'' , (i'' , refl , (⊑ₒ-refl , ⊑ᵢ-refl)) ↓ₑ-⊑ₒ-i'-aux op' {o''} {i''} p | no ¬q with i (op') | i' (op') ↓ₑ-⊑ₒ-i'-aux op' {o''} {i''} refl | no ¬q | nothing | just .(o'' , i'') = o'' , (i'' , refl , (⊑ₒ-refl , ⊑ᵢ-refl)) ↓ₑ-⊑ₒ-i'-aux op' {o''} {imap i''} refl | no ¬q | just (o''' , (imap i''')) | just .(o'' , (imap i'')) = (o''' ∪ₒ o'') , (imap (∪ᵢ-aux i''' i'') , (refl , (∪ₒ-inr , ∪ᵢ-inr))) -- EFFECT ANNOTATION OF AN INTERRUPT THAT WAS NOT ACTED WITH lkpᵢ-↓ₑ-neq : {o o' : O} {i i' : I} {op op' : Σₛ} → ¬ op ≡ op' → lkpᵢ op' i ≡ just (o' , i') → ------------------------------------------------------------------------------------------------------- Σ[ o'' ∈ O ] Σ[ i'' ∈ I ] (lkpᵢ op' (proj₂ (op ↓ₑ (o , i))) ≡ just (o'' , i'') × o' ⊑ₒ o'' × i' ⊑ᵢ i'') lkpᵢ-↓ₑ-neq {omap o} {o'} {imap i} {imap i'} {op} {op'} p q with i (op) ... | nothing = o' , imap i' , q , ⊑ₒ-refl , ⊑ᵢ-refl lkpᵢ-↓ₑ-neq {omap o} {o'} {imap i} {imap i'} {op} {op'} p q | just (o'' , imap i'') with decₛ op op' ... | yes r with p r ... | () lkpᵢ-↓ₑ-neq {omap o} {o'} {imap i} {imap i'} {op} {op'} p q | just (o'' , imap i'') | no ¬r with i (op') | i'' (op') lkpᵢ-↓ₑ-neq {omap o} {.o'''} {imap i} {imap i'} {op} {op'} p refl | just (o'' , imap i'') | no ¬r | just (o''' , .(imap i')) | nothing = o''' , imap i' , refl , ⊑ₒ-refl , ⊑ᵢ-refl ... | just (o''' , imap i''') | just (o'''' , imap i'''') with q lkpᵢ-↓ₑ-neq {omap o} {.o'''} {imap i} {imap .i'''} {op} {op'} p q | just (o'' , imap i'') | no ¬r | just (o''' , imap i''') | just (o'''' , imap i'''') | refl = (o''' ∪ₒ o'''') , (imap i''') ∪ᵢ (imap i'''') , refl , ∪ₒ-inl , ∪ᵢ-inl lkpᵢ-↓ₑ-neq-⊑ : {o o' : O} {i i' : I} {op op' : Σₛ} → ¬ op ≡ op' → (o' , i') ⊑ lkpᵢ op' i → -------------------------------------------- (o' , i') ⊑ lkpᵢ op' (proj₂ (op ↓ₑ (o , i))) lkpᵢ-↓ₑ-neq-⊑ {o = o} {i = i} p q with ⊑-just q ... | o'' , i'' , r with lkpᵢ-↓ₑ-neq {o = o} {i = i} p r ... | o''' , i''' , s , t , u rewrite s = ⊑-trans q r (t , u) -- NEXT DEFINED EFFECT ANNOTATION UNDER SUBTYPING EFFECT ANNOTATIONS lkpᵢ-nextₒ : {o'' : O} {i i' i'' : I} {op : Σₛ} → i ⊑ᵢ i' → lkpᵢ op i ≡ just (o'' , i'') → O lkpᵢ-nextₒ {o''} {i} {i'} {i''} {op} (rel p) q = proj₁ (p op q) lkpᵢ-nextᵢ : {o'' : O} {i i' i'' : I} {op : Σₛ} → i ⊑ᵢ i' → lkpᵢ op i ≡ just (o'' , i'') → I lkpᵢ-nextᵢ {o''} {i} {i'} {i''} {op} (rel p) q = proj₁ (proj₂ (p op q)) lkpᵢ-next-eq : {o'' : O} {i i' i'' : I} {op : Σₛ} → (p : i ⊑ᵢ i') → (q : lkpᵢ op i ≡ just (o'' , i'')) → ------------------------------------------------ lkpᵢ op i' ≡ just (lkpᵢ-nextₒ p q , lkpᵢ-nextᵢ p q) lkpᵢ-next-eq {o''} {i} {i'} {i''} {op} (rel p) q = proj₁ (proj₂ (proj₂ (p op q))) lkpᵢ-next-⊑ₒ : {o'' : O} {i i' i'' : I} {op : Σₛ} → (p : i ⊑ᵢ i') → (q : lkpᵢ op i ≡ just (o'' , i'')) → ----------------------------------- o'' ⊑ₒ lkpᵢ-nextₒ p q lkpᵢ-next-⊑ₒ {o''} {i} {i'} {i''} {op} (rel p) q = proj₁ (proj₂ (proj₂ (proj₂ (p op q)))) lkpᵢ-next-⊑ᵢ : {o'' : O} {i i' i'' : I} {op : Σₛ} → (p : i ⊑ᵢ i') → (q : lkpᵢ op i ≡ just (o'' , i'')) → ----------------------------------- i'' ⊑ᵢ lkpᵢ-nextᵢ p q lkpᵢ-next-⊑ᵢ {o''} {i} {i'} {i''} {op} (rel p) q = proj₂ (proj₂ (proj₂ (proj₂ (p op q)))) -- ACTION OF INTERRUPTS ON EFFECT ANNOTATIONS IS MONOTONIC mutual ↓ₑ-monotonicₒ : {o o' : O} {i i' : I} {op : Σₛ} → o ⊑ₒ o' → i ⊑ᵢ i' → ------------------------------------------------ proj₁ (op ↓ₑ (o , i)) ⊑ₒ proj₁ (op ↓ₑ (o' , i')) ↓ₑ-monotonicₒ {omap o} {omap o'} {imap i} {imap i'} {op} p (rel q) = ↓ₑ-monotonicₒ-aux (i op) (i' op) refl refl where ↓ₑ-monotonicₒ-aux : (oi oi' : Maybe (O × I)) → i op ≡ oi → i' op ≡ oi' → ---------------------------- ↓ₑ-auxₒ op oi (omap o) ⊑ₒ ↓ₑ-auxₒ op oi' (omap o') ↓ₑ-monotonicₒ-aux nothing nothing r s = p ↓ₑ-monotonicₒ-aux nothing (just (omap o''' , imap i''')) r s = ⊑ₒ-trans p ∪ₒ-inl ↓ₑ-monotonicₒ-aux (just (omap o'' , imap i'')) nothing r s with trans (sym s) (proj₁ (proj₂ (proj₂ (q op r)))) ... | () ↓ₑ-monotonicₒ-aux (just (omap o'' , imap i'')) (just (omap o''' , imap i''')) r s with trans (sym s) (proj₁ (proj₂ (proj₂ (q op r)))) ... | t = ∪ₒ-fun p (⊑ₒ-trans (proj₁ (proj₂ (proj₂ (proj₂ (q op r))))) (subst (λ o → o ⊑ₒ omap o''') (inj-pair₁ (inj-just t)) ⊑ₒ-refl)) ↓ₑ-monotonicᵢ : {o o' : O} {i i' : I} {op : Σₛ} → o ⊑ₒ o' → i ⊑ᵢ i' → ------------------------------------------------ proj₂ (op ↓ₑ (o , i)) ⊑ᵢ proj₂ (op ↓ₑ (o' , i')) ↓ₑ-monotonicᵢ {omap o} {omap o'} {imap i} {imap i'} {op} p (rel q) = ↓ₑ-monotonicᵢ-aux (i op) (i' op) refl refl where ↓ₑ-monotonicᵢ-aux : (oi oi' : Maybe (O × I)) → oi ≡ i op → oi' ≡ i' op → ----------------------------------------- ↓ₑ-auxᵢ op oi (imap i) ⊑ᵢ ↓ₑ-auxᵢ op oi' (imap i') ↓ₑ-monotonicᵢ-aux nothing nothing r s = rel q ↓ₑ-monotonicᵢ-aux nothing (just (omap o''' , imap i''')) r s = ⊑ᵢ-trans (rel (λ op' {o''''} {i''''} t → ↓ₑ-monotonicᵢ-aux' op' o'''' i'''' t)) (∪ᵢ-inl {(imap i') [ op ↦ nothing ]ᵢ} {imap i'''}) where ↓ₑ-monotonicᵢ-aux' : (op' : Σₛ) → (o'''' : O) → (i'''' : I) → i op' ≡ just (o'''' , i'''') → -------------------------------------------------------------------- Σ[ o''''' ∈ O ] Σ[ i''''' ∈ I ] ((if op ≡ op' then nothing else i' op') ≡ just (o''''' , i''''') × (o'''' ⊑ₒ o''''') × (i'''' ⊑ᵢ i''''')) ↓ₑ-monotonicᵢ-aux' op' o'''' i'''' t with decₛ op op' ↓ₑ-monotonicᵢ-aux' op' o'''' i'''' t | yes refl with trans r t ... | () ↓ₑ-monotonicᵢ-aux' op' o'''' i'''' t | no ¬u = lkpᵢ-nextₒ (rel q) t , lkpᵢ-nextᵢ (rel q) t , lkpᵢ-next-eq (rel q) t , lkpᵢ-next-⊑ₒ (rel q) t , lkpᵢ-next-⊑ᵢ (rel q) t ↓ₑ-monotonicᵢ-aux (just (omap o'' , imap i'')) nothing r s with trans s (proj₁ (proj₂ (proj₂ (q op (sym r))))) ... | () ↓ₑ-monotonicᵢ-aux (just (omap o'' , imap i'')) (just (omap o''' , imap i''')) r s = ∪ᵢ-fun {_} {imap i''} {_} {imap i'''} (rel λ op' {o''''} {i''''} t → ↓ₑ-monotonicᵢ-aux' op' o'''' i'''' t) (subst (λ i → imap i'' ⊑ᵢ i) (sym (inj-pair₂ (inj-just (trans s (proj₁ (proj₂ (proj₂ (q op (sym r))))))))) (proj₂ (proj₂ (proj₂ (proj₂ (q op (sym r))))))) where ↓ₑ-monotonicᵢ-aux' : (op' : Σₛ) → (o'''' : O) → (i'''' : I) → lkpᵢ op' (imap i [ op ↦ nothing ]ᵢ) ≡ just (o'''' , i'''') → -------------------------- Σ[ o''''' ∈ O ] Σ[ i''''' ∈ I ] (lkpᵢ op' (imap i' [ op ↦ nothing ]ᵢ) ≡ just (o''''' , i''''') × (o'''' ⊑ₒ o''''') × (i'''' ⊑ᵢ i''''')) ↓ₑ-monotonicᵢ-aux' op' o'''' i'''' t with decₛ op op' ↓ₑ-monotonicᵢ-aux' op' o'''' i'''' t | no ¬u = lkpᵢ-nextₒ (rel q) t , lkpᵢ-nextᵢ (rel q) t , lkpᵢ-next-eq (rel q) t , lkpᵢ-next-⊑ₒ (rel q) t , lkpᵢ-next-⊑ᵢ (rel q) t -- GENERALISED ACTION OF INTERRUPTS ON EFFECT ANNOTATIONS IS MONOTONIC mutual ↓↓ₑ-monotonicₒ : {o o' : O} {i i' : I} → (ops : List Σₛ) → o ⊑ₒ o' → i ⊑ᵢ i' → ---------------------------------------------------- proj₁ (ops ↓↓ₑ (o , i)) ⊑ₒ proj₁ (ops ↓↓ₑ (o' , i')) ↓↓ₑ-monotonicₒ {omap o} {omap o'} {imap i} {imap i'} [] p q = p ↓↓ₑ-monotonicₒ (op ∷ ops) p q = ↓ₑ-monotonicₒ (↓↓ₑ-monotonicₒ ops p q) (↓↓ₑ-monotonicᵢ ops p q) ↓↓ₑ-monotonicᵢ : {o o' : O} {i i' : I} → (ops : List Σₛ) → o ⊑ₒ o' → i ⊑ᵢ i' → ---------------------------------------------------- proj₂ (ops ↓↓ₑ (o , i)) ⊑ᵢ proj₂ (ops ↓↓ₑ (o' , i')) ↓↓ₑ-monotonicᵢ [] p q = q ↓↓ₑ-monotonicᵢ (op ∷ ops) p q = ↓ₑ-monotonicᵢ (↓↓ₑ-monotonicₒ ops p q) (↓↓ₑ-monotonicᵢ ops p q) -- INCLUSION INTO GENERALLY ACTED UPON EFFECT ANNOTATION ↓↓ₑ-⊑ₒ : {o : O} {i : I} → (ops : List Σₛ) → -------------------------- o ⊑ₒ proj₁ (ops ↓↓ₑ (o , i)) ↓↓ₑ-⊑ₒ [] = ⊑ₒ-refl ↓↓ₑ-⊑ₒ (op ∷ ops) = ⊑ₒ-trans (↓↓ₑ-⊑ₒ ops) (↓ₑ-⊑ₒ {op = op}) -- A PATH OF INTERRUPT NAMES THAT REVEALS THE GIVEN SIGNAL IN AN EFFECT ANNOTATION data _`at_`in_,_ (op : Σₛ) : List Σₛ → O → I → Set where stop : {o : O} {i : I} → op ∈ₒ o → ------------------- op `at [] `in o , i next : {o o' : O} {i i' : I} {op' : Σₛ} {ops : List Σₛ} → lkpᵢ op' i ≡ just (o' , i') → op `at ops `in o' , i' → ----------------------------- op `at (op' ∷ ops) `in o , i -- ACTING ON AN ANNOTATION WITH EMPTY SIGNALS PART JUST REVEALS THE INNER LAYER IF THE INTERRUPTS MATCH ↓ₑ-∅-↦-≡ : {op : Σₛ} {o : O} {i : I} → ----------------------------- op ↓ₑ (∅ₒ , imap (λ op' → if op' ≡ op then just (o , i) else nothing)) ≡ (o , i) ↓ₑ-∅-↦-≡ {op} {o} {i} with decₛ op op ↓ₑ-∅-↦-≡ {op} {omap o} {i} | yes refl = cong₂ (λ x y → x , y) (∪ₒ-lunit (omap o)) (trans (cong (λ i' → i' ∪ᵢ i) ↓ₑ-∅-↦-≡-aux) (∪ᵢ-lunit i)) where ↓ₑ-∅-↦-≡-aux : imap (λ op' → if op ≡ op' then nothing else (if op' ≡ op then just (omap o , i) else nothing)) ≡ ∅ᵢ ↓ₑ-∅-↦-≡-aux = cong imap (fun-ext ↓ₑ-∅-↦-≡-aux-aux) where ↓ₑ-∅-↦-≡-aux-aux : (op' : Σₛ) → --------------------------------------------------------------------------------- (if op ≡ op' then nothing else (if op' ≡ op then just (omap o , i) else nothing)) ≡ nothing ↓ₑ-∅-↦-≡-aux-aux op' with decₛ op op' ... | yes refl = refl ... | no ¬p = ite-≢ (λ q → ¬p (sym q)) ↓ₑ-∅-↦-≡ {op} {o} {i} | no ¬p = ⊥-elim (¬p refl) -- ACTING ON AN ANNOTATION WITH EMPTY SIGNALS IS IDEMPOTENT IF THE INTERRUPTS DO NOT MATCH ↓ₑ-∅-↦-≢ : {op op' : Σₛ} {o : O} {i : I} → op ≢ op' → ----------------------------- op' ↓ₑ (∅ₒ , imap (λ op'' → if op'' ≡ op then just (o , i) else nothing)) ≡ (∅ₒ , imap (λ op'' → if op'' ≡ op then just (o , i) else nothing)) ↓ₑ-∅-↦-≢ {op} {op'} p with decₛ op' op ↓ₑ-∅-↦-≢ {op} {.op} p | yes refl = ⊥-elim (p refl) ↓ₑ-∅-↦-≢ {op} {op'} p | no ¬q = refl -- A MINIMAL EFFECT ANNOTATION SUCH THAT A GIVEN PATH OF INTERRUPTS REVEALS THE GIVEN SIGNAL NAME mutual ⦃⦃_↦_⦄⦄ₒ : List Σₛ → Σₛ → O ⦃⦃ [] ↦ op ⦄⦄ₒ = omap (λ op' → if op ≡ op' then just tt else nothing) ⦃⦃ op' ∷ ops ↦ op ⦄⦄ₒ = ∅ₒ ⦃⦃_↦_⦄⦄ᵢ : List Σₛ → Σₛ → I ⦃⦃ [] ↦ op ⦄⦄ᵢ = ∅ᵢ ⦃⦃ op' ∷ ops ↦ op ⦄⦄ᵢ = imap (λ op'' → if op'' ≡ op' then just (⦃⦃ ops ↦ op ⦄⦄ₒ , ⦃⦃ ops ↦ op ⦄⦄ᵢ) else nothing) -- IF THERE IS A PATH TO A SIGNAL IN AN EFFECT ANNOTATION, THE MINIMAL EFFECT ANNOTATION IS INCLUDED IN IT mutual `at-minₒ : {op : Σₛ} {ops : List Σₛ} {o : O} {i : I} → op `at ops `in o , i → ---------------------- ⦃⦃ ops ↦ op ⦄⦄ₒ ⊑ₒ o `at-minₒ {op} {_} {omap o} (stop p) op' with decₛ op op' `at-minₒ {.op'} {.[]} {omap o} (stop p) op' | yes refl = λ _ → p `at-minₒ {op} {.[]} {omap o} (stop p) op'' | no ¬q = λ () `at-minₒ (next p q) op'' = λ () `at-minᵢ : {op : Σₛ} {ops : List Σₛ} {o : O} {i : I} → op `at ops `in o , i → ---------------------- ⦃⦃ ops ↦ op ⦄⦄ᵢ ⊑ᵢ i `at-minᵢ (stop p) = rel (λ op'' → λ ()) `at-minᵢ {op} (next {o} {o'} {i} {i'} {op'} {ops} p q) = rel (λ op'' {o''} {i''} r → `at-minᵢ-aux r) where `at-minᵢ-aux : {op'' : Σₛ} {o'' : O} {i'' : I} → lkpᵢ op'' ⦃⦃ op' ∷ ops ↦ op ⦄⦄ᵢ ≡ just (o'' , i'') → --------------------------------------------------- Σ[ o''' ∈ O ] Σ[ i''' ∈ I ] (lkpᵢ op'' i ≡ just (o''' , i''') × (o'' ⊑ₒ o''') × (i'' ⊑ᵢ i''')) `at-minᵢ-aux {op''} p with decₛ op'' op' `at-minᵢ-aux {op'} refl | yes refl = o' , i' , p , `at-minₒ q , `at-minᵢ q -- SUBPATHS OF (INTERRUPT) NAMES data _⊆_ : List Σₛ → List Σₛ → Set where [] : {ops' : List Σₛ} → ---------------- [] ⊆ ops' ∷-≡ : {op : Σₛ} {ops ops' : List Σₛ} → ops ⊆ ops' → ------------------------ (op ∷ ops) ⊆ (op ∷ ops') ∷-≢ : {op op' : Σₛ} {ops ops' : List Σₛ} → op ≢ op' → (op ∷ ops) ⊆ ops' → ------------------------- (op ∷ ops) ⊆ (op' ∷ ops') mutual ∷-≢-swap : {op op' : Σₛ} {ops ops' : List Σₛ} → op ≢ op' → (op ∷ ops) ⊆ (op' ∷ op ∷ ops') → -------------------------------- (op ∷ ops) ⊆ (op ∷ op' ∷ ops') ∷-≢-swap {op} {.op} {ops} {ops'} p (∷-≡ q) = ∷-≡ q ∷-≢-swap {op} {op'} {ops} {ops'} p (∷-≢ q (∷-≡ r)) = ∷-≡ (∷-∷ r) ∷-≢-swap {op} {op'} {ops} {ops'} p (∷-≢ q (∷-≢ r s)) = ⊥-elim (r refl) ∷-∷ : {op' : Σₛ} {ops : List Σₛ} → {ops' : List Σₛ} → ops ⊆ ops' → ------------------- ops ⊆ (op' ∷ ops') ∷-∷ [] = [] ∷-∷ {op'} (∷-≡ {op} p) with decₛ op op' ∷-∷ {.op} (∷-≡ {op} p) | yes refl = ∷-≡ (∷-∷ p) ∷-∷ {op'} (∷-≡ {op} p) | no ¬q = ∷-≢ ¬q (∷-≡ p) ∷-∷ {op'} (∷-≢ {op} {op''} p q) with decₛ op op' ∷-∷ {.op} (∷-≢ {op} {op''} p q) | yes refl = ∷-≢-swap p (∷-≢ p (∷-∷ q)) ∷-∷ {op'} (∷-≢ {op} {op''} p q) | no ¬r = ∷-≢ ¬r (∷-≢ p q) -- IF A SUBPATH OF INTERRUPTS REVEALS A SIGNAL, THEN ACTING WITH THE WHOLE PATH ALSO REVEALS IT ⊆-↓↓ : {op : Σₛ} {ops ops' : List Σₛ} → ops ⊆ ops' → --------------------------------------------------------------- op ∈ₒ proj₁ (reverse ops' ↓↓ₑ (⦃⦃ ops ↦ op ⦄⦄ₒ , ⦃⦃ ops ↦ op ⦄⦄ᵢ)) ⊆-↓↓ {op} {ops} {ops'} [] = (↓↓ₑ-⊑ₒ (reverse ops')) op ⊆-↓↓-aux where ⊆-↓↓-aux : (if op ≡ op then just tt else nothing) ≡ just tt ⊆-↓↓-aux with decₛ op op ⊆-↓↓-aux | yes refl = refl ⊆-↓↓-aux | no ¬p = ⊥-elim (¬p refl) ⊆-↓↓ {op} (∷-≡ {op'} {ops} {ops'} p) = subst (λ ops'' → op ∈ₒ proj₁ (ops'' ↓↓ₑ (⦃⦃ (op' ∷ ops) ↦ op ⦄⦄ₒ , ⦃⦃ (op' ∷ ops) ↦ op ⦄⦄ᵢ))) (sym (unfold-reverse op' ops')) (subst (λ oi → op ∈ₒ proj₁ oi) (sym (↓↓ₑ-act (reverse ops') [ op' ])) (subst (λ oi → op ∈ₒ proj₁ (reverse ops' ↓↓ₑ oi)) (sym ↓ₑ-∅-↦-≡) (⊆-↓↓ p))) ⊆-↓↓ {op} (∷-≢ {op'} {op''} {ops} {ops'} p q) = subst (λ ops'' → op ∈ₒ proj₁ (ops'' ↓↓ₑ (⦃⦃ (op' ∷ ops) ↦ op ⦄⦄ₒ , ⦃⦃ (op' ∷ ops) ↦ op ⦄⦄ᵢ))) (sym (unfold-reverse op'' ops')) (subst (λ oi → op ∈ₒ proj₁ oi) (sym (↓↓ₑ-act (reverse ops') [ op'' ])) (subst (λ oi → op ∈ₒ proj₁ (reverse ops' ↓↓ₑ oi)) (sym (↓ₑ-∅-↦-≢ p)) (⊆-↓↓ q))) -- IF A PATH REVEALS A SIGNAL IN A UNION OF EFFECT ANNOTATIONS, THE PATH REVEALS THE SIGNAL IN ONE OF THE SUMMANDS `at-⊎ : {op : Σₛ} {ops : List Σₛ} {o o' : O} {i i' : I} → op `at ops `in (o ∪ₒ o') , (i ∪ᵢ i') → ------------------------------------------------- (op `at ops `in o , i) ⊎ (op `at ops `in o' , i') `at-⊎ {op} {ops} {omap o} {omap o'} {i} {i'} (stop p) = `at-⊎-aux p (o op) (o' op) refl refl where `at-⊎-aux : (∪ₒ-aux o o' op ≡ just tt) → (t t' : Maybe ⊤) → o op ≡ t → o' op ≡ t' → ----------------------------------------------------------- (op `at ops `in omap o , i) ⊎ (op `at ops `in omap o' , i') `at-⊎-aux p nothing nothing q r with o op | o' op `at-⊎-aux () nothing nothing q r | nothing | nothing `at-⊎-aux p nothing nothing q () | nothing | just tt `at-⊎-aux p nothing (just tt) q r = inj₂ (stop r) `at-⊎-aux p (just tt) t' q r = inj₁ (stop q) `at-⊎ {op} {_} {o} {o'} {imap i} {imap i'} (next {o''} {o'''} {i''} {i'''} {op'} {ops} p q) = `at-⊎-aux p q (i op') (i' op') refl refl where `at-⊎-aux : ∪ᵢ-aux i i' op' ≡ just (o''' , i''') → op `at ops `in o''' , i''' → (oi oi' : Maybe (O × I)) → i op' ≡ oi → i' op' ≡ oi' → --------------------------------------------------------------------------- (op `at (op' ∷ ops) `in o , imap i) ⊎ (op `at (op' ∷ ops) `in o' , imap i') `at-⊎-aux p q nothing nothing r s with i op' | i' op' `at-⊎-aux () q nothing nothing r s | nothing | nothing `at-⊎-aux p q nothing nothing r () | nothing | just _ `at-⊎-aux p q nothing (just (o'''' , i'''')) r s = inj₂ (next (trans (sym (`at-⊎-aux-aux r s)) p) q) where `at-⊎-aux-aux : i op' ≡ nothing → i' op' ≡ just (o'''' , i'''') → ------------------------------- ∪ᵢ-aux i i' op' ≡ i' op' `at-⊎-aux-aux r s with i op' | i' op' `at-⊎-aux-aux r s | nothing | just _ = refl `at-⊎-aux p q (just (o'''' , i'''')) nothing r s = inj₁ (next (trans (sym (`at-⊎-aux-aux r s)) p) q) where `at-⊎-aux-aux : i op' ≡ just (o'''' , i'''') → i' op' ≡ nothing → ------------------------------- ∪ᵢ-aux i i' op' ≡ i op' `at-⊎-aux-aux r s with i op' | i' op' `at-⊎-aux-aux r s | just _ | nothing = refl `at-⊎-aux p q (just (o'''' , i'''')) (just (o''''' , i''''')) r s with ∪ᵢ-∪ₒ {i = imap i} {i' = imap i'} p r s | ∪ᵢ-∪ᵢ {i = imap i} {i' = imap i'} p r s ... | refl | refl with `at-⊎ q ... | inj₁ t = inj₁ (next r t) ... | inj₂ t = inj₂ (next s t) -- IF ACTING WITH A PATH REVEALS A SIGNAL, THEN THERE IS A SUBPATH TO THAT SIGNAL ↓↓-⊆-rw : (o : O) (i : I) (op : Σₛ) (ops : List Σₛ) → ---------------------------------------------------------------- reverse (op ∷ ops) ↓↓ₑ (o , i) ≡ reverse ops ↓↓ₑ (op ↓ₑ (o , i)) ↓↓-⊆-rw o i op ops = trans (cong (λ ops' → ops' ↓↓ₑ (o , i)) (unfold-reverse op ops)) (↓↓ₑ-act (reverse ops) [ op ]) ↓↓-⊆ : {op : Σₛ} → (ops : List Σₛ) → {o : O} {i : I} → op ∈ₒ proj₁ (reverse ops ↓↓ₑ (o , i)) → ---------------------------------------------------------- Σ[ ops' ∈ List Σₛ ] (ops' ⊆ ops × (op `at ops' `in o , i)) ↓↓-⊆ [] p = [] , [] , stop p ↓↓-⊆ {op} (op' ∷ ops) {omap o} {imap i} p rewrite ↓↓-⊆-rw (omap o) (imap i) op' ops = ↓↓-⊆-aux (i op') refl where ↓↓-⊆-aux : (oi : Maybe (O × I)) → i op' ≡ oi → ---------------------------------------------------------------------------- Σ[ ops' ∈ List Σₛ ] (ops' ⊆ (op' ∷ ops) × (op `at ops' `in omap o , imap i)) ↓↓-⊆-aux nothing q with ↓↓-⊆ ops p ... | ops' , r , s rewrite q = ops' , ∷-∷ r , s ↓↓-⊆-aux (just (omap o' , imap i')) q with ↓↓-⊆ ops p ... | ops' , r , s rewrite q with `at-⊎ {o = omap o} {o' = omap o'} {i' = imap i'} s ... | inj₁ t = ↓↓-⊆-aux-aux ops' r t where ↓↓-⊆-aux-aux : (ops' : List Σₛ) → ops' ⊆ ops → (op `at ops' `in omap o , ((imap i) [ op' ↦ nothing ]ᵢ)) → ------------------------------------------------------------------------------- Σ[ ops'' ∈ List Σₛ ] (ops'' ⊆ (op' ∷ ops) × (op `at ops'' `in omap o , imap i)) ↓↓-⊆-aux-aux [] r (stop t) = [] , [] , stop t ↓↓-⊆-aux-aux (op'' ∷ ops'') r (next t u) with decₛ op' op'' ... | no ¬v = op'' ∷ ops'' , ∷-≢ (λ w → ¬v (sym w)) r , next t u ... | inj₂ t = op' ∷ ops' , ∷-≡ r , next q t -- ENVELOPING THE EFFECT ANNOTATION REDUCTION WITH MLTIPLE INTERRUPT ACTIONS ↓↓ₑ-⊑ₒ-act : {o : O} {i : I} → (ops : List Σₛ) → (op : Σₛ) → ---------------------------------------------------------- proj₁ (ops ↓↓ₑ (o , i)) ⊑ₒ proj₁ (ops ↓↓ₑ (op ↓ₑ (o , i))) ↓↓ₑ-⊑ₒ-act {o} {i} ops op op' p rewrite sym (reverse-involutive ops) with ↓↓-⊆ (reverse ops) p ... | ops' , q , r with ⊆-↓↓ {op'} (∷-∷ {op} q) ... | s with ↓↓ₑ-monotonicₒ (reverse (op ∷ reverse ops)) (`at-minₒ r) (`at-minᵢ r) op' s ... | t rewrite ↓↓-⊆-rw o i op (reverse ops) | reverse-involutive ops = t ",16173,True,3678.356770851109,median "infixr 6 _∷_ data List (A : Set) : Set where [] : List A _∷_ : A -> List A -> List A postulate Bool : Set t : Bool long : List Bool long = _∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t (_∷_ t []))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) ",16209,True,7774.554480909921,median "open util/ordering [State] as ord pred test27 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Grain0,Chicken0 + Grain0,Farmer0 + Chicken0 + Grain0] }}}}}} } run test27 for 4 expect 1 pred test16 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0] }}}}}} } run test16 for 4 expect 1 pred test42 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0] }}}}}} } run test42 for 4 expect 0 pred test39 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test39 for 4 expect 1 pred test46 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 solvePuzzle[] }}}}}} } run test46 for 4 expect 0 pred test2 { some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { no Farmer Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 far = State1->Fox0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test2 for 4 expect 0 pred test40 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test40 for 4 expect 1 pred test21 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test21 for 4 expect 1 pred test17 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,Chicken0,none,Farmer0] }}}}}} } run test17 for 4 expect 1 pred test8 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test8 for 4 expect 0 pred test26 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Grain0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test26 for 4 expect 1 pred test35 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test35 for 4 expect 1 pred test43 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,none,Farmer0 + Chicken0] }}}}}} } run test43 for 4 expect 1 pred test1 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test1 for 4 expect 1 pred test10 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test10 for 4 expect 1 pred test20 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0,Fox0,none,Farmer0] }}}}}} } run test20 for 4 expect 1 pred test14 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Grain0,Fox0 + Chicken0] }}}}}} } run test14 for 4 expect 0 pred test30 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test30 for 4 expect 1 pred test31 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test31 for 4 expect 1 pred test12 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test12 for 4 expect 0 pred test6 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test6 for 4 expect 1 pred test41 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,none,Farmer0 + Chicken0] }}}}}} } run test41 for 4 expect 1 pred test45 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0,Farmer0 + Fox0] }}}}}} } run test45 for 4 expect 1 pred test19 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test19 for 4 expect 1 pred test29 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test29 for 4 expect 1 pred test25 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test25 for 4 expect 0 pred test48 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test48 for 4 expect 0 pred test54 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test54 for 4 expect 0 pred test50 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State1->Farmer0 + State3->Farmer0 + State3->Fox0 far = State0->Fox0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test50 for 4 expect 0 pred test24 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,none,none,Farmer0 + Grain0] }}}}}} } run test24 for 4 expect 0 pred test49 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test49 for 4 expect 1 pred test34 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test34 for 4 expect 1 pred test47 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test47 for 4 expect 0 pred test28 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Grain0,Chicken0] }}}}}} } run test28 for 4 expect 0 pred test9 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test9 for 4 expect 1 pred test51 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Fox0 + State2->Grain0 + State3->Farmer0 + State3->Fox0 + State3->Grain0 far = State2->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test51 for 4 expect 0 pred test7 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test7 for 4 expect 1 pred test37 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test37 for 4 expect 1 pred test33 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test33 for 4 expect 1 pred test18 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,Chicken0,none,Farmer0] }}}}}} } run test18 for 4 expect 1 pred test44 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Grain0,none,none,Farmer0 + Grain0] }}}}}} } run test44 for 4 expect 1 pred test22 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Fox0 + Chicken0 + Grain0,none] }}}}}} } run test22 for 4 expect 0 pred test23 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test23 for 4 expect 1 pred test5 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Farmer0, Fox0, Chicken0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 no Grain Object = Farmer0 + Fox0 + Chicken0 eats = Fox0->Chicken0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test5 for 4 expect 0 pred test53 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Fox0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test53 for 4 expect 0 pred test13 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test13 for 4 expect 0 pred test4 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Grain0: Grain {some disj Farmer0, Fox0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 no Chicken Grain = Grain0 Object = Farmer0 + Fox0 + Grain0 no eats State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test4 for 4 expect 0 pred test15 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Grain0,none,Farmer0] }}}}}} } run test15 for 4 expect 0 pred test3 { some disj Farmer0: Farmer {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 no Fox Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Chicken0 + State0->Grain0 + State1->Grain0 + State2->Farmer0 + State2->Grain0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test3 for 4 expect 0 pred test56 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test56 for 4 expect 1 pred test11 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test11 for 4 expect 1 pred test36 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,Fox0,Farmer0 + Fox0 + Chicken0] }}}}}} } run test36 for 4 expect 1 pred test32 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test32 for 4 expect 1 pred test38 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Grain0] }}}}}} } run test38 for 4 expect 1 pred test55 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test55 for 4 expect 0 pred test52 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Chicken0 + State1->Grain0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test52 for 4 expect 0",16148,True,6302.51561688828,median "/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ parser grammar HiveParser; options { tokenVocab=HiveLexer; language=Java; } tokens { TOK_INSERT; TOK_QUERY; TOK_SELECT; TOK_SELECTDI; TOK_SELEXPR; TOK_FROM; TOK_TAB; TOK_PARTSPEC; TOK_PARTVAL; TOK_DIR; TOK_LOCAL_DIR; TOK_TABREF; TOK_SUBQUERY; TOK_INSERT_INTO; TOK_DESTINATION; TOK_ALLCOLREF; TOK_TABLE_OR_COL; TOK_FUNCTION; TOK_FUNCTIONDI; TOK_FUNCTIONSTAR; TOK_WHERE; TOK_OP_EQ; TOK_OP_NE; TOK_OP_LE; TOK_OP_LT; TOK_OP_GE; TOK_OP_GT; TOK_OP_DIV; TOK_OP_ADD; TOK_OP_SUB; TOK_OP_MUL; TOK_OP_MOD; TOK_OP_BITAND; TOK_OP_BITNOT; TOK_OP_BITOR; TOK_OP_BITXOR; TOK_OP_AND; TOK_OP_OR; TOK_OP_NOT; TOK_OP_LIKE; TOK_TRUE; TOK_FALSE; TOK_TRANSFORM; TOK_SERDE; TOK_SERDENAME; TOK_SERDEPROPS; TOK_EXPLIST; TOK_ALIASLIST; TOK_GROUPBY; TOK_ROLLUP_GROUPBY; TOK_CUBE_GROUPBY; TOK_GROUPING_SETS; TOK_GROUPING_SETS_EXPRESSION; TOK_HAVING; TOK_ORDERBY; TOK_CLUSTERBY; TOK_DISTRIBUTEBY; TOK_SORTBY; TOK_UNION; TOK_JOIN; TOK_LEFTOUTERJOIN; TOK_RIGHTOUTERJOIN; TOK_FULLOUTERJOIN; TOK_UNIQUEJOIN; TOK_CROSSJOIN; TOK_LOAD; TOK_EXPORT; TOK_IMPORT; TOK_NULL; TOK_ISNULL; TOK_ISNOTNULL; TOK_TINYINT; TOK_SMALLINT; TOK_INT; TOK_BIGINT; TOK_BOOLEAN; TOK_FLOAT; TOK_DOUBLE; TOK_DATE; TOK_DATETIME; TOK_TIMESTAMP; TOK_STRING; TOK_BINARY; TOK_DECIMAL; TOK_LIST; TOK_STRUCT; TOK_MAP; TOK_UNIONTYPE; TOK_COLTYPELIST; TOK_CREATEDATABASE; TOK_CREATETABLE; TOK_TRUNCATETABLE; TOK_CREATEINDEX; TOK_CREATEINDEX_INDEXTBLNAME; TOK_DEFERRED_REBUILDINDEX; TOK_DROPINDEX; TOK_DROPTABLE_PROPERTIES; TOK_LIKETABLE; TOK_DESCTABLE; TOK_DESCFUNCTION; TOK_ALTERTABLE_PARTITION; TOK_ALTERTABLE_RENAME; TOK_ALTERTABLE_ADDCOLS; TOK_ALTERTABLE_RENAMECOL; TOK_ALTERTABLE_RENAMEPART; TOK_ALTERTABLE_REPLACECOLS; TOK_ALTERTABLE_ADDPARTS; TOK_ALTERTABLE_DROPPARTS; TOK_ALTERTABLE_ALTERPARTS; TOK_ALTERTABLE_ALTERPARTS_PROTECTMODE; TOK_ALTERTABLE_TOUCH; TOK_ALTERTABLE_ARCHIVE; TOK_ALTERTABLE_UNARCHIVE; TOK_ALTERTABLE_SERDEPROPERTIES; TOK_ALTERTABLE_SERIALIZER; TOK_TABLE_PARTITION; TOK_ALTERTABLE_FILEFORMAT; TOK_ALTERTABLE_LOCATION; TOK_ALTERTABLE_PROPERTIES; TOK_ALTERTABLE_CHANGECOL_AFTER_POSITION; TOK_ALTERINDEX_REBUILD; TOK_ALTERINDEX_PROPERTIES; TOK_MSCK; TOK_SHOWDATABASES; TOK_SHOWTABLES; TOK_SHOWCOLUMNS; TOK_SHOWFUNCTIONS; TOK_SHOWPARTITIONS; TOK_SHOW_CREATETABLE; TOK_SHOW_TABLESTATUS; TOK_SHOW_TBLPROPERTIES; TOK_SHOWLOCKS; TOK_LOCKTABLE; TOK_UNLOCKTABLE; TOK_SWITCHDATABASE; TOK_DROPDATABASE; TOK_DROPTABLE; TOK_DATABASECOMMENT; TOK_TABCOLLIST; TOK_TABCOL; TOK_TABLECOMMENT; TOK_TABLEPARTCOLS; TOK_TABLEBUCKETS; TOK_TABLEROWFORMAT; TOK_TABLEROWFORMATFIELD; TOK_TABLEROWFORMATCOLLITEMS; TOK_TABLEROWFORMATMAPKEYS; TOK_TABLEROWFORMATLINES; TOK_TBLORCFILE; TOK_TBLSEQUENCEFILE; TOK_TBLTEXTFILE; TOK_TBLRCFILE; TOK_TABLEFILEFORMAT; TOK_FILEFORMAT_GENERIC; TOK_OFFLINE; TOK_ENABLE; TOK_DISABLE; TOK_READONLY; TOK_NO_DROP; TOK_STORAGEHANDLER; TOK_ALTERTABLE_CLUSTER_SORT; TOK_NOT_CLUSTERED; TOK_NOT_SORTED; TOK_TABCOLNAME; TOK_TABLELOCATION; TOK_PARTITIONLOCATION; TOK_TABLEBUCKETSAMPLE; TOK_TABLESPLITSAMPLE; TOK_PERCENT; TOK_LENGTH; TOK_ROWCOUNT; TOK_TMP_FILE; TOK_TABSORTCOLNAMEASC; TOK_TABSORTCOLNAMEDESC; TOK_STRINGLITERALSEQUENCE; TOK_CHARSETLITERAL; TOK_CREATEFUNCTION; TOK_DROPFUNCTION; TOK_CREATEVIEW; TOK_DROPVIEW; TOK_ALTERVIEW_AS; TOK_ALTERVIEW_PROPERTIES; TOK_DROPVIEW_PROPERTIES; TOK_ALTERVIEW_ADDPARTS; TOK_ALTERVIEW_DROPPARTS; TOK_ALTERVIEW_RENAME; TOK_VIEWPARTCOLS; TOK_EXPLAIN; TOK_TABLESERIALIZER; TOK_TABLEPROPERTIES; TOK_TABLEPROPLIST; TOK_INDEXPROPERTIES; TOK_INDEXPROPLIST; TOK_TABTYPE; TOK_LIMIT; TOK_TABLEPROPERTY; TOK_IFEXISTS; TOK_IFNOTEXISTS; TOK_ORREPLACE; TOK_HINTLIST; TOK_HINT; TOK_MAPJOIN; TOK_STREAMTABLE; TOK_HOLD_DDLTIME; TOK_HINTARGLIST; TOK_USERSCRIPTCOLNAMES; TOK_USERSCRIPTCOLSCHEMA; TOK_RECORDREADER; TOK_RECORDWRITER; TOK_LEFTSEMIJOIN; TOK_LATERAL_VIEW; TOK_TABALIAS; TOK_ANALYZE; TOK_CREATEROLE; TOK_DROPROLE; TOK_GRANT; TOK_REVOKE; TOK_SHOW_GRANT; TOK_PRIVILEGE_LIST; TOK_PRIVILEGE; TOK_PRINCIPAL_NAME; TOK_USER; TOK_GROUP; TOK_ROLE; TOK_GRANT_WITH_OPTION; TOK_PRIV_ALL; TOK_PRIV_ALTER_METADATA; TOK_PRIV_ALTER_DATA; TOK_PRIV_DROP; TOK_PRIV_INDEX; TOK_PRIV_LOCK; TOK_PRIV_SELECT; TOK_PRIV_SHOW_DATABASE; TOK_PRIV_CREATE; TOK_PRIV_OBJECT; TOK_PRIV_OBJECT_COL; TOK_GRANT_ROLE; TOK_REVOKE_ROLE; TOK_SHOW_ROLE_GRANT; TOK_SHOWINDEXES; TOK_INDEXCOMMENT; TOK_DESCDATABASE; TOK_DATABASEPROPERTIES; TOK_DATABASELOCATION; TOK_DBPROPLIST; TOK_ALTERDATABASE_PROPERTIES; TOK_ALTERTABLE_ALTERPARTS_MERGEFILES; TOK_TABNAME; TOK_TABSRC; TOK_RESTRICT; TOK_CASCADE; TOK_TABLESKEWED; TOK_TABCOLVALUE; TOK_TABCOLVALUE_PAIR; TOK_TABCOLVALUES; TOK_ALTERTABLE_SKEWED; TOK_ALTERTBLPART_SKEWED_LOCATION; TOK_SKEWED_LOCATIONS; TOK_SKEWED_LOCATION_LIST; TOK_SKEWED_LOCATION_MAP; TOK_STOREDASDIRS; TOK_PARTITIONINGSPEC; TOK_PTBLFUNCTION; TOK_WINDOWDEF; TOK_WINDOWSPEC; TOK_WINDOWVALUES; TOK_WINDOWRANGE; TOK_IGNOREPROTECTION; } // Package headers @header { import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; } @members { private static final Log LOG = LogFactory.getLog(HiveParser.class.getName()); Stack msgs = new Stack(); private static HashMap xlateMap; static { xlateMap = new HashMap(); // Keywords xlateMap.put(""KW_TRUE"", ""TRUE""); xlateMap.put(""KW_FALSE"", ""FALSE""); xlateMap.put(""KW_ALL"", ""ALL""); xlateMap.put(""KW_AND"", ""AND""); xlateMap.put(""KW_OR"", ""OR""); xlateMap.put(""KW_NOT"", ""NOT""); xlateMap.put(""KW_LIKE"", ""LIKE""); xlateMap.put(""KW_ASC"", ""ASC""); xlateMap.put(""KW_DESC"", ""DESC""); xlateMap.put(""KW_ORDER"", ""ORDER""); xlateMap.put(""KW_BY"", ""BY""); xlateMap.put(""KW_GROUP"", ""GROUP""); xlateMap.put(""KW_WHERE"", ""WHERE""); xlateMap.put(""KW_FROM"", ""FROM""); xlateMap.put(""KW_AS"", ""AS""); xlateMap.put(""KW_SELECT"", ""SELECT""); xlateMap.put(""KW_DISTINCT"", ""DISTINCT""); xlateMap.put(""KW_INSERT"", ""INSERT""); xlateMap.put(""KW_OVERWRITE"", ""OVERWRITE""); xlateMap.put(""KW_OUTER"", ""OUTER""); xlateMap.put(""KW_JOIN"", ""JOIN""); xlateMap.put(""KW_LEFT"", ""LEFT""); xlateMap.put(""KW_RIGHT"", ""RIGHT""); xlateMap.put(""KW_FULL"", ""FULL""); xlateMap.put(""KW_ON"", ""ON""); xlateMap.put(""KW_PARTITION"", ""PARTITION""); xlateMap.put(""KW_PARTITIONS"", ""PARTITIONS""); xlateMap.put(""KW_TABLE"", ""TABLE""); xlateMap.put(""KW_TABLES"", ""TABLES""); xlateMap.put(""KW_TBLPROPERTIES"", ""TBLPROPERTIES""); xlateMap.put(""KW_SHOW"", ""SHOW""); xlateMap.put(""KW_MSCK"", ""MSCK""); xlateMap.put(""KW_DIRECTORY"", ""DIRECTORY""); xlateMap.put(""KW_LOCAL"", ""LOCAL""); xlateMap.put(""KW_TRANSFORM"", ""TRANSFORM""); xlateMap.put(""KW_USING"", ""USING""); xlateMap.put(""KW_CLUSTER"", ""CLUSTER""); xlateMap.put(""KW_DISTRIBUTE"", ""DISTRIBUTE""); xlateMap.put(""KW_SORT"", ""SORT""); xlateMap.put(""KW_UNION"", ""UNION""); xlateMap.put(""KW_LOAD"", ""LOAD""); xlateMap.put(""KW_DATA"", ""DATA""); xlateMap.put(""KW_INPATH"", ""INPATH""); xlateMap.put(""KW_IS"", ""IS""); xlateMap.put(""KW_NULL"", ""NULL""); xlateMap.put(""KW_CREATE"", ""CREATE""); xlateMap.put(""KW_EXTERNAL"", ""EXTERNAL""); xlateMap.put(""KW_ALTER"", ""ALTER""); xlateMap.put(""KW_DESCRIBE"", ""DESCRIBE""); xlateMap.put(""KW_DROP"", ""DROP""); xlateMap.put(""KW_REANME"", ""REANME""); xlateMap.put(""KW_TO"", ""TO""); xlateMap.put(""KW_COMMENT"", ""COMMENT""); xlateMap.put(""KW_BOOLEAN"", ""BOOLEAN""); xlateMap.put(""KW_TINYINT"", ""TINYINT""); xlateMap.put(""KW_SMALLINT"", ""SMALLINT""); xlateMap.put(""KW_INT"", ""INT""); xlateMap.put(""KW_BIGINT"", ""BIGINT""); xlateMap.put(""KW_FLOAT"", ""FLOAT""); xlateMap.put(""KW_DOUBLE"", ""DOUBLE""); xlateMap.put(""KW_DATE"", ""DATE""); xlateMap.put(""KW_DATETIME"", ""DATETIME""); xlateMap.put(""KW_TIMESTAMP"", ""TIMESTAMP""); xlateMap.put(""KW_STRING"", ""STRING""); xlateMap.put(""KW_BINARY"", ""BINARY""); xlateMap.put(""KW_ARRAY"", ""ARRAY""); xlateMap.put(""KW_MAP"", ""MAP""); xlateMap.put(""KW_REDUCE"", ""REDUCE""); xlateMap.put(""KW_PARTITIONED"", ""PARTITIONED""); xlateMap.put(""KW_CLUSTERED"", ""CLUSTERED""); xlateMap.put(""KW_SORTED"", ""SORTED""); xlateMap.put(""KW_INTO"", ""INTO""); xlateMap.put(""KW_BUCKETS"", ""BUCKETS""); xlateMap.put(""KW_ROW"", ""ROW""); xlateMap.put(""KW_FORMAT"", ""FORMAT""); xlateMap.put(""KW_DELIMITED"", ""DELIMITED""); xlateMap.put(""KW_FIELDS"", ""FIELDS""); xlateMap.put(""KW_TERMINATED"", ""TERMINATED""); xlateMap.put(""KW_COLLECTION"", ""COLLECTION""); xlateMap.put(""KW_ITEMS"", ""ITEMS""); xlateMap.put(""KW_KEYS"", ""KEYS""); xlateMap.put(""KW_KEY_TYPE"", ""\\$KEY\\$""); xlateMap.put(""KW_LINES"", ""LINES""); xlateMap.put(""KW_STORED"", ""STORED""); xlateMap.put(""KW_SEQUENCEFILE"", ""SEQUENCEFILE""); xlateMap.put(""KW_TEXTFILE"", ""TEXTFILE""); xlateMap.put(""KW_INPUTFORMAT"", ""INPUTFORMAT""); xlateMap.put(""KW_OUTPUTFORMAT"", ""OUTPUTFORMAT""); xlateMap.put(""KW_LOCATION"", ""LOCATION""); xlateMap.put(""KW_TABLESAMPLE"", ""TABLESAMPLE""); xlateMap.put(""KW_BUCKET"", ""BUCKET""); xlateMap.put(""KW_OUT"", ""OUT""); xlateMap.put(""KW_OF"", ""OF""); xlateMap.put(""KW_CAST"", ""CAST""); xlateMap.put(""KW_ADD"", ""ADD""); xlateMap.put(""KW_REPLACE"", ""REPLACE""); xlateMap.put(""KW_COLUMNS"", ""COLUMNS""); xlateMap.put(""KW_RLIKE"", ""RLIKE""); xlateMap.put(""KW_REGEXP"", ""REGEXP""); xlateMap.put(""KW_TEMPORARY"", ""TEMPORARY""); xlateMap.put(""KW_FUNCTION"", ""FUNCTION""); xlateMap.put(""KW_EXPLAIN"", ""EXPLAIN""); xlateMap.put(""KW_EXTENDED"", ""EXTENDED""); xlateMap.put(""KW_SERDE"", ""SERDE""); xlateMap.put(""KW_WITH"", ""WITH""); xlateMap.put(""KW_SERDEPROPERTIES"", ""SERDEPROPERTIES""); xlateMap.put(""KW_LIMIT"", ""LIMIT""); xlateMap.put(""KW_SET"", ""SET""); xlateMap.put(""KW_PROPERTIES"", ""TBLPROPERTIES""); xlateMap.put(""KW_VALUE_TYPE"", ""\\$VALUE\\$""); xlateMap.put(""KW_ELEM_TYPE"", ""\\$ELEM\\$""); // Operators xlateMap.put(""DOT"", "".""); xlateMap.put(""COLON"", "":""); xlateMap.put(""COMMA"", "",""); xlateMap.put(""SEMICOLON"", "");""); xlateMap.put(""LPAREN"", ""(""); xlateMap.put(""RPAREN"", "")""); xlateMap.put(""LSQUARE"", ""[""); xlateMap.put(""RSQUARE"", ""]""); xlateMap.put(""EQUAL"", ""=""); xlateMap.put(""NOTEQUAL"", ""<>""); xlateMap.put(""EQUAL_NS"", ""<=>""); xlateMap.put(""LESSTHANOREQUALTO"", ""<=""); xlateMap.put(""LESSTHAN"", ""<""); xlateMap.put(""GREATERTHANOREQUALTO"", "">=""); xlateMap.put(""GREATERTHAN"", "">""); xlateMap.put(""DIVIDE"", ""/""); xlateMap.put(""PLUS"", ""+""); xlateMap.put(""MINUS"", ""-""); xlateMap.put(""STAR"", ""*""); xlateMap.put(""MOD"", ""%""); xlateMap.put(""AMPERSAND"", ""&""); xlateMap.put(""TILDE"", ""~""); xlateMap.put(""BITWISEOR"", ""|""); xlateMap.put(""BITWISEXOR"", ""^""); xlateMap.put(""CharSetLiteral"", ""\\\\'""); } public static Collection getKeywords() { return xlateMap.values(); } private static String xlate(String name) { String ret = xlateMap.get(name); if (ret == null) { ret = name; } return ret; } } @rulecatch { catch (RecognitionException e) { reportError(e); throw e; } } //----------------------- Rules for parsing selectClause ----------------------------- // select a,b,c ... selectClause @init { msgs.push(""select clause""); } @after { msgs.pop(); } : KW_SELECT hintClause? (((KW_ALL | dist=KW_DISTINCT)? selectList) | (transform=KW_TRANSFORM selectTrfmClause)) | trfmClause ; selectList @init { msgs.push(""select list""); } @after { msgs.pop(); } : selectItem ( COMMA selectItem )* ; selectTrfmClause @init { msgs.push(""transform clause""); } @after { msgs.pop(); } : LPAREN selectExpressionList RPAREN inSerde=rowFormat inRec=recordWriter KW_USING StringLiteral ( KW_AS ((LPAREN (aliasList | columnNameTypeList) RPAREN) | (aliasList | columnNameTypeList)))? outSerde=rowFormat outRec=recordReader ; hintClause @init { msgs.push(""hint clause""); } @after { msgs.pop(); } : DIVIDE STAR PLUS hintList STAR DIVIDE ; hintList @init { msgs.push(""hint list""); } @after { msgs.pop(); } : hintItem (COMMA hintItem)* ; hintItem @init { msgs.push(""hint item""); } @after { msgs.pop(); } : hintName (LPAREN hintArgs RPAREN)? ; hintName @init { msgs.push(""hint name""); } @after { msgs.pop(); } : KW_MAPJOIN | KW_STREAMTABLE | KW_HOLD_DDLTIME ; hintArgs @init { msgs.push(""hint arguments""); } @after { msgs.pop(); } : hintArgName (COMMA hintArgName)* ; hintArgName @init { msgs.push(""hint argument name""); } @after { msgs.pop(); } : identifier ; selectItem @init { msgs.push(""selection target""); } @after { msgs.pop(); } : ( selectExpression (KW_OVER ws=window_specification )? ((KW_AS? identifier) | (KW_AS LPAREN identifier (COMMA identifier)* RPAREN))? ) ; trfmClause @init { msgs.push(""transform clause""); } @after { msgs.pop(); } : ( KW_MAP selectExpressionList | KW_REDUCE selectExpressionList ) inSerde=rowFormat inRec=recordWriter KW_USING StringLiteral ( KW_AS ((LPAREN (aliasList | columnNameTypeList) RPAREN) | (aliasList | columnNameTypeList)))? outSerde=rowFormat outRec=recordReader ; selectExpression @init { msgs.push(""select expression""); } @after { msgs.pop(); } : expression | tableAllColumns ; selectExpressionList @init { msgs.push(""select expression list""); } @after { msgs.pop(); } : selectExpression (COMMA selectExpression)* ; //---------------------- Rules for windowing clauses ------------------------------- window_clause @init { msgs.push(""window_clause""); } @after { msgs.pop(); } : KW_WINDOW window_defn (COMMA window_defn)* ; window_defn @init { msgs.push(""window_defn""); } @after { msgs.pop(); } : Identifier KW_AS window_specification ; window_specification @init { msgs.push(""window_specification""); } @after { msgs.pop(); } : (Identifier | ( LPAREN Identifier? partitioningSpec? window_frame? RPAREN)) ; window_frame : window_range_expression | window_value_expression ; window_range_expression @init { msgs.push(""window_range_expression""); } @after { msgs.pop(); } : KW_ROWS sb=window_frame_start_boundary KW_ROWS KW_BETWEEN s=window_frame_boundary KW_AND end=window_frame_boundary ; window_value_expression @init { msgs.push(""window_value_expression""); } @after { msgs.pop(); } : KW_RANGE sb=window_frame_start_boundary KW_RANGE KW_BETWEEN s=window_frame_boundary KW_AND end=window_frame_boundary ; window_frame_start_boundary @init { msgs.push(""windowframestartboundary""); } @after { msgs.pop(); } : KW_UNBOUNDED KW_PRECEDING KW_CURRENT KW_ROW Number KW_PRECEDING ; window_frame_boundary @init { msgs.push(""windowframeboundary""); } @after { msgs.pop(); } : KW_UNBOUNDED (r=KW_PRECEDING|r=KW_FOLLOWING) KW_CURRENT KW_ROW Number (d=KW_PRECEDING | d=KW_FOLLOWING ) ; tableAllColumns : STAR | tableName DOT STAR ; // (table|column) tableOrColumn @init { msgs.push(""table or column identifier""); } @after { msgs.pop(); } : identifier ; expressionList @init { msgs.push(""expression list""); } @after { msgs.pop(); } : expression (COMMA expression)* ; aliasList @init { msgs.push(""alias list""); } @after { msgs.pop(); } : identifier (COMMA identifier)* ; //----------------------- Rules for parsing fromClause ------------------------------ // from [col1, col2, col3] table1, [col4, col5] table2 fromClause @init { msgs.push(""from clause""); } @after { msgs.pop(); } : KW_FROM joinSource ; joinSource @init { msgs.push(""join source""); } @after { msgs.pop(); } : fromSource ( joinToken fromSource (KW_ON expression)? )* | uniqueJoinToken uniqueJoinSource (COMMA uniqueJoinSource)+ ; uniqueJoinSource @init { msgs.push(""join source""); } @after { msgs.pop(); } : KW_PRESERVE? fromSource uniqueJoinExpr ; uniqueJoinExpr @init { msgs.push(""unique join expression list""); } @after { msgs.pop(); } : LPAREN e1+=expression (COMMA e1+=expression)* RPAREN ; uniqueJoinToken @init { msgs.push(""unique join""); } @after { msgs.pop(); } : KW_UNIQUEJOIN ; joinToken @init { msgs.push(""join type specifier""); } @after { msgs.pop(); } : KW_JOIN | KW_INNER KW_JOIN | KW_CROSS KW_JOIN | KW_LEFT KW_OUTER KW_JOIN | KW_RIGHT KW_OUTER KW_JOIN | KW_FULL KW_OUTER KW_JOIN | KW_LEFT KW_SEMI KW_JOIN ; lateralView @init {msgs.push(""lateral view""); } @after {msgs.pop(); } : KW_LATERAL KW_VIEW function tableAlias KW_AS identifier (COMMA identifier)* ; tableAlias @init {msgs.push(""table alias""); } @after {msgs.pop(); } : identifier ; fromSource @init { msgs.push(""from source""); } @after { msgs.pop(); } : ((Identifier LPAREN) | tableSource | subQuerySource) (lateralView)* ; tableBucketSample @init { msgs.push(""table bucket sample specification""); } @after { msgs.pop(); } : KW_TABLESAMPLE LPAREN KW_BUCKET (numerator=Number) KW_OUT KW_OF (denominator=Number) (KW_ON expr+=expression (COMMA expr+=expression)*)? RPAREN ; splitSample @init { msgs.push(""table split sample specification""); } @after { msgs.pop(); } : KW_TABLESAMPLE LPAREN (numerator=Number) (percent=KW_PERCENT|KW_ROWS) RPAREN | KW_TABLESAMPLE LPAREN (numerator=ByteLengthLiteral) RPAREN ; tableSample @init { msgs.push(""table sample specification""); } @after { msgs.pop(); } : tableBucketSample | splitSample ; tableSource @init { msgs.push(""table source""); } @after { msgs.pop(); } : tabname=tableName (ts=tableSample)? (alias=identifier)? ; tableName @init { msgs.push(""table name""); } @after { msgs.pop(); } : db=identifier DOT tab=identifier | tab=identifier ; viewName @init { msgs.push(""view name""); } @after { msgs.pop(); } : (db=identifier DOT)? view=identifier ; subQuerySource @init { msgs.push(""subquery source""); } @after { msgs.pop(); } : LPAREN queryStatementExpression RPAREN identifier ; //---------------------- Rules for parsing PTF clauses ----------------------------- partitioningSpec @init { msgs.push(""partitioningSpec clause""); } @after { msgs.pop(); } : partitionByClause orderByClause? orderByClause distributeByClause sortByClause? sortByClause clusterByClause ; partitionTableFunctionSource @init { msgs.push(""partitionTableFunctionSource clause""); } @after { msgs.pop(); } : subQuerySource | tableSource | partitionedTableFunction ; partitionedTableFunction @init { msgs.push(""ptf clause""); } @after { msgs.pop(); } : name=Identifier LPAREN KW_ON ptfsrc=partitionTableFunctionSource partitioningSpec? ((Identifier LPAREN expression RPAREN ) )? RPAREN alias=Identifier? ; //----------------------- Rules for parsing whereClause ----------------------------- // where a=b and ... whereClause @init { msgs.push(""where clause""); } @after { msgs.pop(); } : KW_WHERE searchCondition ; searchCondition @init { msgs.push(""search condition""); } @after { msgs.pop(); } : expression ; //----------------------------------------------------------------------------------- // group by a,b groupByClause @init { msgs.push(""group by clause""); } @after { msgs.pop(); } : KW_GROUP KW_BY groupByExpression ( COMMA groupByExpression )* ((rollup=KW_WITH KW_ROLLUP) | (cube=KW_WITH KW_CUBE)) ? (sets=KW_GROUPING KW_SETS LPAREN groupingSetExpression ( COMMA groupingSetExpression)* RPAREN ) ? ; groupingSetExpression @init {msgs.push(""grouping set expression""); } @after {msgs.pop(); } : groupByExpression | LPAREN groupByExpression (COMMA groupByExpression)* RPAREN | LPAREN RPAREN ; groupByExpression @init { msgs.push(""group by expression""); } @after { msgs.pop(); } : expression ; havingClause @init { msgs.push(""having clause""); } @after { msgs.pop(); } : KW_HAVING havingCondition ; havingCondition @init { msgs.push(""having condition""); } @after { msgs.pop(); } : expression ; // order by a,b orderByClause @init { msgs.push(""order by clause""); } @after { msgs.pop(); } : KW_ORDER KW_BY LPAREN columnRefOrder ( COMMA columnRefOrder)* RPAREN | KW_ORDER KW_BY columnRefOrder ( COMMA columnRefOrder)* ; clusterByClause @init { msgs.push(""cluster by clause""); } @after { msgs.pop(); } : KW_CLUSTER KW_BY LPAREN expression (COMMA expression)* RPAREN | KW_CLUSTER KW_BY expression ((COMMA))* ; partitionByClause @init { msgs.push(""partition by clause""); } @after { msgs.pop(); } : KW_PARTITION KW_BY LPAREN expression (COMMA expression)* RPAREN | KW_PARTITION KW_BY expression ((COMMA))* ; distributeByClause @init { msgs.push(""distribute by clause""); } @after { msgs.pop(); } : KW_DISTRIBUTE KW_BY LPAREN expression (COMMA expression)* RPAREN | KW_DISTRIBUTE KW_BY expression ((COMMA))* ; sortByClause @init { msgs.push(""sort by clause""); } @after { msgs.pop(); } : KW_SORT KW_BY LPAREN columnRefOrder ( COMMA columnRefOrder)* RPAREN | KW_SORT KW_BY columnRefOrder ( (COMMA))* ; // fun(par1, par2, par3) function @init { msgs.push(""function specification""); } @after { msgs.pop(); } : functionName LPAREN ( (star=STAR) | (dist=KW_DISTINCT)? (selectExpression (COMMA selectExpression)*)? ) RPAREN ; functionName @init { msgs.push(""function name""); } @after { msgs.pop(); } : // Keyword IF is also a function name KW_IF | KW_ARRAY | KW_MAP | KW_STRUCT | KW_UNIONTYPE | identifier ; castExpression @init { msgs.push(""cast expression""); } @after { msgs.pop(); } : KW_CAST LPAREN expression KW_AS primitiveType RPAREN ; caseExpression @init { msgs.push(""case expression""); } @after { msgs.pop(); } : KW_CASE expression (KW_WHEN expression KW_THEN expression)+ (KW_ELSE expression)? KW_END ; whenExpression @init { msgs.push(""case expression""); } @after { msgs.pop(); } : KW_CASE ( KW_WHEN expression KW_THEN expression)+ (KW_ELSE expression)? KW_END ; constant @init { msgs.push(""constant""); } @after { msgs.pop(); } : Number | StringLiteral | stringLiteralSequence | BigintLiteral | SmallintLiteral | TinyintLiteral | DecimalLiteral | charSetStringLiteral | booleanValue ; stringLiteralSequence : StringLiteral StringLiteral+ ; charSetStringLiteral @init { msgs.push(""character string literal""); } @after { msgs.pop(); } : csName=CharSetName csLiteral=CharSetLiteral ; expression @init { msgs.push(""expression specification""); } @after { msgs.pop(); } : precedenceOrExpression ; atomExpression : KW_NULL | constant | function | castExpression | caseExpression | whenExpression | tableOrColumn | LPAREN expression RPAREN ; precedenceFieldExpression : atomExpression ((LSQUARE expression RSQUARE) | (DOT identifier))* ; precedenceUnaryOperator : PLUS | MINUS | TILDE ; nullCondition : KW_NULL | KW_NOT KW_NULL ; precedenceUnaryPrefixExpression : (precedenceUnaryOperator)* precedenceFieldExpression ; precedenceUnarySuffixExpression : precedenceUnaryPrefixExpression (a=KW_IS nullCondition)? ; precedenceBitwiseXorOperator : BITWISEXOR ; precedenceBitwiseXorExpression : precedenceUnarySuffixExpression (precedenceBitwiseXorOperator precedenceUnarySuffixExpression)* ; precedenceStarOperator : STAR | DIVIDE | MOD | DIV ; precedenceStarExpression : precedenceBitwiseXorExpression (precedenceStarOperator precedenceBitwiseXorExpression)* ; precedencePlusOperator : PLUS | MINUS ; precedencePlusExpression : precedenceStarExpression (precedencePlusOperator precedenceStarExpression)* ; precedenceAmpersandOperator : AMPERSAND ; precedenceAmpersandExpression : precedencePlusExpression (precedenceAmpersandOperator precedencePlusExpression)* ; precedenceBitwiseOrOperator : BITWISEOR ; precedenceBitwiseOrExpression : precedenceAmpersandExpression (precedenceBitwiseOrOperator precedenceAmpersandExpression)* ; // Equal operators supporting NOT prefix precedenceEqualNegatableOperator : KW_LIKE | KW_RLIKE | KW_REGEXP ; precedenceEqualOperator : precedenceEqualNegatableOperator | EQUAL | EQUAL_NS | NOTEQUAL | LESSTHANOREQUALTO | LESSTHAN | GREATERTHANOREQUALTO | GREATERTHAN ; precedenceEqualExpression : (left=precedenceBitwiseOrExpression ) ( (KW_NOT precedenceEqualNegatableOperator notExpr=precedenceBitwiseOrExpression) | (precedenceEqualOperator equalExpr=precedenceBitwiseOrExpression) | (KW_NOT KW_IN expressions) | (KW_IN expressions) | ( KW_NOT KW_BETWEEN (min=precedenceBitwiseOrExpression) KW_AND (max=precedenceBitwiseOrExpression) ) | ( KW_BETWEEN (min=precedenceBitwiseOrExpression) KW_AND (max=precedenceBitwiseOrExpression) ) )* ; expressions : LPAREN expression (COMMA expression)* RPAREN ; precedenceNotOperator : KW_NOT ; precedenceNotExpression : (precedenceNotOperator)* precedenceEqualExpression ; precedenceAndOperator : KW_AND ; precedenceAndExpression : precedenceNotExpression (precedenceAndOperator precedenceNotExpression)* ; precedenceOrOperator : KW_OR ; precedenceOrExpression : precedenceAndExpression (precedenceOrOperator precedenceAndExpression)* ; booleanValue : KW_TRUE | KW_FALSE ; tableOrPartition : tableName partitionSpec? ; partitionSpec : KW_PARTITION LPAREN partitionVal (COMMA partitionVal )* RPAREN ; partitionVal : identifier (EQUAL constant)? ; dropPartitionSpec : KW_PARTITION LPAREN dropPartitionVal (COMMA dropPartitionVal )* RPAREN ; dropPartitionVal : identifier dropPartitionOperator constant ; dropPartitionOperator : EQUAL | NOTEQUAL | LESSTHANOREQUALTO | LESSTHAN | GREATERTHANOREQUALTO | GREATERTHAN ; sysFuncNames : KW_AND | KW_OR | KW_NOT | KW_LIKE | KW_IF | KW_CASE | KW_WHEN | KW_TINYINT | KW_SMALLINT | KW_INT | KW_BIGINT | KW_FLOAT | KW_DOUBLE | KW_BOOLEAN | KW_STRING | KW_BINARY | KW_ARRAY | KW_MAP | KW_STRUCT | KW_UNIONTYPE | EQUAL | EQUAL_NS | NOTEQUAL | LESSTHANOREQUALTO | LESSTHAN | GREATERTHANOREQUALTO | GREATERTHAN | DIVIDE | PLUS | MINUS | STAR | MOD | DIV | AMPERSAND | TILDE | BITWISEOR | BITWISEXOR | KW_RLIKE | KW_REGEXP | KW_IN | KW_BETWEEN ; descFuncNames : sysFuncNames | StringLiteral | identifier ; identifier : Identifier | nonReserved ; nonReserved : KW_TRUE | KW_FALSE | KW_LIKE | KW_EXISTS | KW_ASC | KW_DESC | KW_ORDER | KW_GROUP | KW_BY | KW_AS | KW_INSERT | KW_OVERWRITE | KW_OUTER | KW_LEFT | KW_RIGHT | KW_FULL | KW_PARTITION | KW_PARTITIONS | KW_TABLE | KW_TABLES | KW_COLUMNS | KW_INDEX | KW_INDEXES | KW_REBUILD | KW_FUNCTIONS | KW_SHOW | KW_MSCK | KW_REPAIR | KW_DIRECTORY | KW_LOCAL | KW_USING | KW_CLUSTER | KW_DISTRIBUTE | KW_SORT | KW_UNION | KW_LOAD | KW_EXPORT | KW_IMPORT | KW_DATA | KW_INPATH | KW_IS | KW_NULL | KW_CREATE | KW_EXTERNAL | KW_ALTER | KW_CHANGE | KW_FIRST | KW_AFTER | KW_DESCRIBE | KW_DROP | KW_RENAME | KW_IGNORE | KW_PROTECTION | KW_TO | KW_COMMENT | KW_BOOLEAN | KW_TINYINT | KW_SMALLINT | KW_INT | KW_BIGINT | KW_FLOAT | KW_DOUBLE | KW_DATE | KW_DATETIME | KW_TIMESTAMP | KW_DECIMAL | KW_STRING | KW_ARRAY | KW_STRUCT | KW_UNIONTYPE | KW_PARTITIONED | KW_CLUSTERED | KW_SORTED | KW_INTO | KW_BUCKETS | KW_ROW | KW_ROWS | KW_FORMAT | KW_DELIMITED | KW_FIELDS | KW_TERMINATED | KW_ESCAPED | KW_COLLECTION | KW_ITEMS | KW_KEYS | KW_KEY_TYPE | KW_LINES | KW_STORED | KW_FILEFORMAT | KW_SEQUENCEFILE | KW_TEXTFILE | KW_RCFILE | KW_ORCFILE | KW_INPUTFORMAT | KW_OUTPUTFORMAT | KW_INPUTDRIVER | KW_OUTPUTDRIVER | KW_OFFLINE | KW_ENABLE | KW_DISABLE | KW_READONLY | KW_NO_DROP | KW_LOCATION | KW_BUCKET | KW_OUT | KW_OF | KW_PERCENT | KW_ADD | KW_REPLACE | KW_RLIKE | KW_REGEXP | KW_TEMPORARY | KW_EXPLAIN | KW_FORMATTED | KW_PRETTY | KW_DEPENDENCY | KW_SERDE | KW_WITH | KW_DEFERRED | KW_SERDEPROPERTIES | KW_DBPROPERTIES | KW_LIMIT | KW_SET | KW_UNSET | KW_TBLPROPERTIES | KW_IDXPROPERTIES | KW_VALUE_TYPE | KW_ELEM_TYPE | KW_MAPJOIN | KW_STREAMTABLE | KW_HOLD_DDLTIME | KW_CLUSTERSTATUS | KW_UTC | KW_UTCTIMESTAMP | KW_LONG | KW_DELETE | KW_PLUS | KW_MINUS | KW_FETCH | KW_INTERSECT | KW_VIEW | KW_IN | KW_DATABASES | KW_MATERIALIZED | KW_SCHEMA | KW_SCHEMAS | KW_GRANT | KW_REVOKE | KW_SSL | KW_UNDO | KW_LOCK | KW_LOCKS | KW_UNLOCK | KW_SHARED | KW_EXCLUSIVE | KW_PROCEDURE | KW_UNSIGNED | KW_WHILE | KW_READ | KW_READS | KW_PURGE | KW_RANGE | KW_ANALYZE | KW_BEFORE | KW_BETWEEN | KW_BOTH | KW_BINARY | KW_CONTINUE | KW_CURSOR | KW_TRIGGER | KW_RECORDREADER | KW_RECORDWRITER | KW_SEMI | KW_LATERAL | KW_TOUCH | KW_ARCHIVE | KW_UNARCHIVE | KW_COMPUTE | KW_STATISTICS | KW_USE | KW_OPTION | KW_CONCATENATE | KW_SHOW_DATABASE | KW_UPDATE | KW_RESTRICT | KW_CASCADE | KW_SKEWED | KW_ROLLUP | KW_CUBE | KW_DIRECTORIES | KW_FOR | KW_GROUPING | KW_SETS | KW_TRUNCATE | KW_NOSCAN | KW_USER | KW_ROLE | KW_INNER ; //----------------------------------------------------------------------------------- // starting rule statement : explainStatement EOF | execStatement EOF ; explainStatement @init { msgs.push(""explain statement""); } @after { msgs.pop(); } : KW_EXPLAIN (explainOptions=KW_EXTENDED|explainOptions=KW_FORMATTED|explainOptions=KW_DEPENDENCY)? execStatement ; execStatement @init { msgs.push(""statement""); } @after { msgs.pop(); } : queryStatementExpression | loadStatement | exportStatement | importStatement | ddlStatement ; loadStatement @init { msgs.push(""load statement""); } @after { msgs.pop(); } : KW_LOAD KW_DATA (islocal=KW_LOCAL)? KW_INPATH (path=StringLiteral) (isoverwrite=KW_OVERWRITE)? KW_INTO KW_TABLE (tab=tableOrPartition) ; exportStatement @init { msgs.push(""export statement""); } @after { msgs.pop(); } : KW_EXPORT KW_TABLE (tab=tableOrPartition) KW_TO (path=StringLiteral) ; importStatement @init { msgs.push(""import statement""); } @after { msgs.pop(); } : KW_IMPORT ((ext=KW_EXTERNAL)? KW_TABLE (tab=tableOrPartition))? KW_FROM (path=StringLiteral) tableLocation? ; ddlStatement @init { msgs.push(""ddl statement""); } @after { msgs.pop(); } : createDatabaseStatement | switchDatabaseStatement | dropDatabaseStatement | createTableStatement | dropTableStatement | truncateTableStatement | alterStatement | descStatement | showStatement | metastoreCheck | createViewStatement | dropViewStatement | createFunctionStatement | createIndexStatement | dropIndexStatement | dropFunctionStatement | analyzeStatement | lockStatement | unlockStatement | createRoleStatement | dropRoleStatement | grantPrivileges | revokePrivileges | showGrants | showRoleGrants | grantRole | revokeRole ; ifExists @init { msgs.push(""if exists clause""); } @after { msgs.pop(); } : KW_IF KW_EXISTS ; restrictOrCascade @init { msgs.push(""restrict or cascade clause""); } @after { msgs.pop(); } : KW_RESTRICT | KW_CASCADE ; ifNotExists @init { msgs.push(""if not exists clause""); } @after { msgs.pop(); } : KW_IF KW_NOT KW_EXISTS ; storedAsDirs @init { msgs.push(""stored as directories""); } @after { msgs.pop(); } : KW_STORED KW_AS KW_DIRECTORIES ; orReplace @init { msgs.push(""or replace clause""); } @after { msgs.pop(); } : KW_OR KW_REPLACE ; ignoreProtection @init { msgs.push(""ignore protection clause""); } @after { msgs.pop(); } : KW_IGNORE KW_PROTECTION ; createDatabaseStatement @init { msgs.push(""create database statement""); } @after { msgs.pop(); } : KW_CREATE (KW_DATABASE|KW_SCHEMA) ifNotExists? name=identifier databaseComment? dbLocation? (KW_WITH KW_DBPROPERTIES dbprops=dbProperties)? ; dbLocation @init { msgs.push(""database location specification""); } @after { msgs.pop(); } : KW_LOCATION locn=StringLiteral ; dbProperties @init { msgs.push(""dbproperties""); } @after { msgs.pop(); } : LPAREN dbPropertiesList RPAREN ; dbPropertiesList @init { msgs.push(""database properties list""); } @after { msgs.pop(); } : keyValueProperty (COMMA keyValueProperty)* ; switchDatabaseStatement @init { msgs.push(""switch database statement""); } @after { msgs.pop(); } : KW_USE identifier ; dropDatabaseStatement @init { msgs.push(""drop database statement""); } @after { msgs.pop(); } : KW_DROP (KW_DATABASE|KW_SCHEMA) ifExists? identifier restrictOrCascade? ; databaseComment @init { msgs.push(""database's comment""); } @after { msgs.pop(); } : KW_COMMENT comment=StringLiteral ; createTableStatement @init { msgs.push(""create table statement""); } @after { msgs.pop(); } : KW_CREATE (ext=KW_EXTERNAL)? KW_TABLE ifNotExists? name=tableName ( like=KW_LIKE likeName=tableName tableLocation? tablePropertiesPrefixed? | (LPAREN columnNameTypeList RPAREN)? tableComment? tablePartition? tableBuckets? tableSkewed? tableRowFormat? tableFileFormat? tableLocation? tablePropertiesPrefixed? (KW_AS selectStatement)? ) ; truncateTableStatement @init { msgs.push(""truncate table statement""); } @after { msgs.pop(); } : KW_TRUNCATE KW_TABLE tablePartitionPrefix ; createIndexStatement @init { msgs.push(""create index statement"");} @after {msgs.pop();} : KW_CREATE KW_INDEX indexName=identifier KW_ON KW_TABLE tab=tableName LPAREN indexedCols=columnNameList RPAREN KW_AS typeName=StringLiteral autoRebuild? indexPropertiesPrefixed? indexTblName? tableRowFormat? tableFileFormat? tableLocation? tablePropertiesPrefixed? indexComment? ; indexComment @init { msgs.push(""comment on an index"");} @after {msgs.pop();} : KW_COMMENT comment=StringLiteral ; autoRebuild @init { msgs.push(""auto rebuild index"");} @after {msgs.pop();} : KW_WITH KW_DEFERRED KW_REBUILD ; indexTblName @init { msgs.push(""index table name"");} @after {msgs.pop();} : KW_IN KW_TABLE indexTbl=tableName ; indexPropertiesPrefixed @init { msgs.push(""table properties with prefix""); } @after { msgs.pop(); } : KW_IDXPROPERTIES indexProperties ; indexProperties @init { msgs.push(""index properties""); } @after { msgs.pop(); } : LPAREN indexPropertiesList RPAREN ; indexPropertiesList @init { msgs.push(""index properties list""); } @after { msgs.pop(); } : keyValueProperty (COMMA keyValueProperty)* ; dropIndexStatement @init { msgs.push(""drop index statement"");} @after {msgs.pop();} : KW_DROP KW_INDEX ifExists? indexName=identifier KW_ON tab=tableName ; dropTableStatement @init { msgs.push(""drop statement""); } @after { msgs.pop(); } : KW_DROP KW_TABLE ifExists? tableName ; alterStatement @init { msgs.push(""alter statement""); } @after { msgs.pop(); } : KW_ALTER ( KW_TABLE alterTableStatementSuffix | KW_VIEW alterViewStatementSuffix | KW_INDEX alterIndexStatementSuffix | KW_DATABASE alterDatabaseStatementSuffix ) ; alterTableStatementSuffix @init { msgs.push(""alter table statement""); } @after { msgs.pop(); } : alterStatementSuffixRename | alterStatementSuffixAddCol | alterStatementSuffixRenameCol | alterStatementSuffixDropPartitions | alterStatementSuffixAddPartitions | alterStatementSuffixTouch | alterStatementSuffixArchive | alterStatementSuffixUnArchive | alterStatementSuffixProperties | alterTblPartitionStatement | alterStatementSuffixSkewedby ; alterViewStatementSuffix @init { msgs.push(""alter view statement""); } @after { msgs.pop(); } : alterViewSuffixProperties | alterStatementSuffixRename | alterStatementSuffixAddPartitions | alterStatementSuffixDropPartitions | name=tableName KW_AS selectStatement ; alterIndexStatementSuffix @init { msgs.push(""alter index statement""); } @after { msgs.pop(); } : indexName=identifier (KW_ON tableNameId=identifier) partitionSpec? ( KW_REBUILD | KW_SET KW_IDXPROPERTIES indexProperties ) ; alterDatabaseStatementSuffix @init { msgs.push(""alter database statement""); } @after { msgs.pop(); } : alterDatabaseSuffixProperties ; alterDatabaseSuffixProperties @init { msgs.push(""alter database properties statement""); } @after { msgs.pop(); } : name=identifier KW_SET KW_DBPROPERTIES dbProperties ; alterStatementSuffixRename @init { msgs.push(""rename statement""); } @after { msgs.pop(); } : oldName=identifier KW_RENAME KW_TO newName=identifier ; alterStatementSuffixAddCol @init { msgs.push(""add column statement""); } @after { msgs.pop(); } : identifier (add=KW_ADD | replace=KW_REPLACE) KW_COLUMNS LPAREN columnNameTypeList RPAREN ; alterStatementSuffixRenameCol @init { msgs.push(""rename column name""); } @after { msgs.pop(); } : identifier KW_CHANGE KW_COLUMN? oldName=identifier newName=identifier colType (KW_COMMENT comment=StringLiteral)? alterStatementChangeColPosition? ; alterStatementChangeColPosition : first=KW_FIRST|KW_AFTER afterCol=identifier ; alterStatementSuffixAddPartitions @init { msgs.push(""add partition statement""); } @after { msgs.pop(); } : identifier KW_ADD ifNotExists? partitionSpec partitionLocation? (partitionSpec partitionLocation?)* ; alterStatementSuffixTouch @init { msgs.push(""touch statement""); } @after { msgs.pop(); } : identifier KW_TOUCH (partitionSpec)* ; alterStatementSuffixArchive @init { msgs.push(""archive statement""); } @after { msgs.pop(); } : identifier KW_ARCHIVE (partitionSpec)* ; alterStatementSuffixUnArchive @init { msgs.push(""unarchive statement""); } @after { msgs.pop(); } : identifier KW_UNARCHIVE (partitionSpec)* ; partitionLocation @init { msgs.push(""partition location""); } @after { msgs.pop(); } : KW_LOCATION locn=StringLiteral ; alterStatementSuffixDropPartitions @init { msgs.push(""drop partition statement""); } @after { msgs.pop(); } : identifier KW_DROP ifExists? dropPartitionSpec (COMMA dropPartitionSpec)* ignoreProtection? ; alterStatementSuffixProperties @init { msgs.push(""alter properties statement""); } @after { msgs.pop(); } : name=identifier KW_SET KW_TBLPROPERTIES tableProperties | name=identifier KW_UNSET KW_TBLPROPERTIES ifExists? tableProperties ; alterViewSuffixProperties @init { msgs.push(""alter view properties statement""); } @after { msgs.pop(); } : name=identifier KW_SET KW_TBLPROPERTIES tableProperties | name=identifier KW_UNSET KW_TBLPROPERTIES ifExists? tableProperties ; alterStatementSuffixSerdeProperties @init { msgs.push(""alter serdes statement""); } @after { msgs.pop(); } : KW_SET KW_SERDE serdeName=StringLiteral (KW_WITH KW_SERDEPROPERTIES tableProperties)? | KW_SET KW_SERDEPROPERTIES tableProperties ; tablePartitionPrefix @init {msgs.push(""table partition prefix"");} @after {msgs.pop();} :name=identifier partitionSpec? ; alterTblPartitionStatement @init {msgs.push(""alter table partition statement"");} @after {msgs.pop();} : tablePartitionPrefix alterTblPartitionStatementSuffix |Identifier KW_PARTITION KW_COLUMN LPAREN columnNameType RPAREN ; alterTblPartitionStatementSuffix @init {msgs.push(""alter table partition statement suffix"");} @after {msgs.pop();} : alterStatementSuffixFileFormat | alterStatementSuffixLocation | alterStatementSuffixProtectMode | alterStatementSuffixMergeFiles | alterStatementSuffixSerdeProperties | alterStatementSuffixRenamePart | alterStatementSuffixBucketNum | alterTblPartitionStatementSuffixSkewedLocation | alterStatementSuffixClusterbySortby ; alterStatementSuffixFileFormat @init {msgs.push(""alter fileformat statement""); } @after {msgs.pop();} : KW_SET KW_FILEFORMAT fileFormat ; alterStatementSuffixClusterbySortby @init {msgs.push(""alter partition cluster by sort by statement"");} @after {msgs.pop();} : KW_NOT KW_CLUSTERED | KW_NOT KW_SORTED | tableBuckets ; alterTblPartitionStatementSuffixSkewedLocation @init {msgs.push(""alter partition skewed location"");} @after {msgs.pop();} : KW_SET KW_SKEWED KW_LOCATION skewedLocations ; skewedLocations @init { msgs.push(""skewed locations""); } @after { msgs.pop(); } : LPAREN skewedLocationsList RPAREN ; skewedLocationsList @init { msgs.push(""skewed locations list""); } @after { msgs.pop(); } : skewedLocationMap (COMMA skewedLocationMap)* ; skewedLocationMap @init { msgs.push(""specifying skewed location map""); } @after { msgs.pop(); } : key=skewedValueLocationElement EQUAL value=StringLiteral ; alterStatementSuffixLocation @init {msgs.push(""alter location"");} @after {msgs.pop();} : KW_SET KW_LOCATION newLoc=StringLiteral ; alterStatementSuffixSkewedby @init {msgs.push(""alter skewed by statement"");} @after{msgs.pop();} :name=identifier tableSkewed | name=identifier KW_NOT KW_SKEWED | name=identifier KW_NOT storedAsDirs ; alterStatementSuffixProtectMode @init { msgs.push(""alter partition protect mode statement""); } @after { msgs.pop(); } : alterProtectMode ; alterStatementSuffixRenamePart @init { msgs.push(""alter table rename partition statement""); } @after { msgs.pop(); } : KW_RENAME KW_TO partitionSpec ; alterStatementSuffixMergeFiles @init { msgs.push(""""); } @after { msgs.pop(); } : KW_CONCATENATE ; alterProtectMode @init { msgs.push(""protect mode specification enable""); } @after { msgs.pop(); } : KW_ENABLE alterProtectModeMode | KW_DISABLE alterProtectModeMode ; alterProtectModeMode @init { msgs.push(""protect mode specification enable""); } @after { msgs.pop(); } : KW_OFFLINE | KW_NO_DROP KW_CASCADE? | KW_READONLY ; alterStatementSuffixBucketNum @init { msgs.push(""""); } @after { msgs.pop(); } : KW_INTO num=Number KW_BUCKETS ; fileFormat @init { msgs.push(""file format specification""); } @after { msgs.pop(); } : KW_SEQUENCEFILE | KW_TEXTFILE | KW_RCFILE | KW_ORCFILE | KW_INPUTFORMAT inFmt=StringLiteral KW_OUTPUTFORMAT outFmt=StringLiteral (KW_INPUTDRIVER inDriver=StringLiteral KW_OUTPUTDRIVER outDriver=StringLiteral)? | genericSpec=identifier ; tabTypeExpr @init { msgs.push(""specifying table types""); } @after { msgs.pop(); } : identifier (DOT (KW_ELEM_TYPE | KW_KEY_TYPE | KW_VALUE_TYPE | identifier))* ; descTabTypeExpr @init { msgs.push(""specifying describe table types""); } @after { msgs.pop(); } : identifier (DOT (KW_ELEM_TYPE | KW_KEY_TYPE | KW_VALUE_TYPE | identifier))* identifier? ; partTypeExpr @init { msgs.push(""specifying table partitions""); } @after { msgs.pop(); } : tabTypeExpr partitionSpec? ; descPartTypeExpr @init { msgs.push(""specifying describe table partitions""); } @after { msgs.pop(); } : descTabTypeExpr partitionSpec? ; descStatement @init { msgs.push(""describe statement""); } @after { msgs.pop(); } : (KW_DESCRIBE|KW_DESC) (descOptions=KW_FORMATTED|descOptions=KW_EXTENDED|descOptions=KW_PRETTY)? (parttype=descPartTypeExpr) | (KW_DESCRIBE|KW_DESC) KW_FUNCTION KW_EXTENDED? (name=descFuncNames) | (KW_DESCRIBE|KW_DESC) KW_DATABASE KW_EXTENDED? (dbName=identifier) ; analyzeStatement @init { msgs.push(""analyze statement""); } @after { msgs.pop(); } : KW_ANALYZE KW_TABLE (parttype=tableOrPartition) KW_COMPUTE KW_STATISTICS ((noscan=KW_NOSCAN) | (partialscan=KW_PARTIALSCAN) | (KW_FOR KW_COLUMNS statsColumnName=columnNameList))? ; showStatement @init { msgs.push(""show statement""); } @after { msgs.pop(); } : KW_SHOW (KW_DATABASES|KW_SCHEMAS) (KW_LIKE showStmtIdentifier)? | KW_SHOW KW_TABLES ((KW_FROM|KW_IN) db_name=identifier)? (KW_LIKE showStmtIdentifier|showStmtIdentifier)? | KW_SHOW KW_COLUMNS (KW_FROM|KW_IN) tabname=tableName ((KW_FROM|KW_IN) db_name=identifier)? | KW_SHOW KW_FUNCTIONS showStmtIdentifier? | KW_SHOW KW_PARTITIONS identifier partitionSpec? | KW_SHOW KW_CREATE KW_TABLE tabName=tableName | KW_SHOW KW_TABLE KW_EXTENDED ((KW_FROM|KW_IN) db_name=identifier)? KW_LIKE showStmtIdentifier partitionSpec? | KW_SHOW KW_TBLPROPERTIES tblName=identifier (LPAREN prptyName=StringLiteral RPAREN)? | KW_SHOW KW_LOCKS (parttype=partTypeExpr)? (isExtended=KW_EXTENDED)? | KW_SHOW (showOptions=KW_FORMATTED)? (KW_INDEX|KW_INDEXES) KW_ON showStmtIdentifier ((KW_FROM|KW_IN) db_name=identifier)? ; lockStatement @init { msgs.push(""lock statement""); } @after { msgs.pop(); } : KW_LOCK KW_TABLE tableName partitionSpec? lockMode ; lockMode @init { msgs.push(""lock mode""); } @after { msgs.pop(); } : KW_SHARED | KW_EXCLUSIVE ; unlockStatement @init { msgs.push(""unlock statement""); } @after { msgs.pop(); } : KW_UNLOCK KW_TABLE tableName partitionSpec? ; createRoleStatement @init { msgs.push(""create role""); } @after { msgs.pop(); } : KW_CREATE KW_ROLE roleName=identifier ; dropRoleStatement @init {msgs.push(""drop role"");} @after {msgs.pop();} : KW_DROP KW_ROLE roleName=identifier ; grantPrivileges @init {msgs.push(""grant privileges"");} @after {msgs.pop();} : KW_GRANT privList=privilegeList privilegeObject? KW_TO principalSpecification (KW_WITH withOption)? ; revokePrivileges @init {msgs.push(""revoke privileges"");} @afer {msgs.pop();} : KW_REVOKE privilegeList privilegeObject? KW_FROM principalSpecification ; grantRole @init {msgs.push(""grant role"");} @after {msgs.pop();} : KW_GRANT KW_ROLE identifier (COMMA identifier)* KW_TO principalSpecification ; revokeRole @init {msgs.push(""revoke role"");} @after {msgs.pop();} : KW_REVOKE KW_ROLE identifier (COMMA identifier)* KW_FROM principalSpecification ; showRoleGrants @init {msgs.push(""show role grants"");} @after {msgs.pop();} : KW_SHOW KW_ROLE KW_GRANT principalName ; showGrants @init {msgs.push(""show grants"");} @after {msgs.pop();} : KW_SHOW KW_GRANT principalName privilegeIncludeColObject? ; privilegeIncludeColObject @init {msgs.push(""privilege object including columns"");} @after {msgs.pop();} : KW_ON (table=KW_TABLE|KW_DATABASE) identifier (LPAREN cols=columnNameList RPAREN)? partitionSpec? ; privilegeObject @init {msgs.push(""privilege subject"");} @after {msgs.pop();} : KW_ON (table=KW_TABLE|KW_DATABASE) identifier partitionSpec? ; privilegeList @init {msgs.push(""grant privilege list"");} @after {msgs.pop();} : privlegeDef (COMMA privlegeDef)* ; privlegeDef @init {msgs.push(""grant privilege"");} @after {msgs.pop();} : privilegeType (LPAREN cols=columnNameList RPAREN)? ; privilegeType @init {msgs.push(""privilege type"");} @after {msgs.pop();} : KW_ALL | KW_ALTER | KW_UPDATE | KW_CREATE | KW_DROP | KW_INDEX | KW_LOCK | KW_SELECT | KW_SHOW_DATABASE ; principalSpecification @init { msgs.push(""user/group/role name list""); } @after { msgs.pop(); } : principalName (COMMA principalName)* ; principalName @init {msgs.push(""user|group|role name"");} @after {msgs.pop();} : KW_USER identifier | KW_GROUP identifier | KW_ROLE identifier ; withOption @init {msgs.push(""grant with option"");} @after {msgs.pop();} : KW_GRANT KW_OPTION ; metastoreCheck @init { msgs.push(""metastore check statement""); } @after { msgs.pop(); } : KW_MSCK (repair=KW_REPAIR)? (KW_TABLE table=identifier partitionSpec? (COMMA partitionSpec)*)? ; createFunctionStatement @init { msgs.push(""create function statement""); } @after { msgs.pop(); } : KW_CREATE KW_TEMPORARY KW_FUNCTION identifier KW_AS StringLiteral ; dropFunctionStatement @init { msgs.push(""drop temporary function statement""); } @after { msgs.pop(); } : KW_DROP KW_TEMPORARY KW_FUNCTION ifExists? identifier ; createViewStatement @init { msgs.push(""create view statement""); } @after { msgs.pop(); } : KW_CREATE (orReplace)? KW_VIEW (ifNotExists)? name=tableName (LPAREN columnNameCommentList RPAREN)? tableComment? viewPartition? tablePropertiesPrefixed? KW_AS selectStatement ; viewPartition @init { msgs.push(""view partition specification""); } @after { msgs.pop(); } : KW_PARTITIONED KW_ON LPAREN columnNameList RPAREN ; dropViewStatement @init { msgs.push(""drop view statement""); } @after { msgs.pop(); } : KW_DROP KW_VIEW ifExists? viewName ; showStmtIdentifier @init { msgs.push(""identifier for show statement""); } @after { msgs.pop(); } : identifier | StringLiteral ; tableComment @init { msgs.push(""table's comment""); } @after { msgs.pop(); } : KW_COMMENT comment=StringLiteral ; tablePartition @init { msgs.push(""table partition specification""); } @after { msgs.pop(); } : KW_PARTITIONED KW_BY LPAREN columnNameTypeList RPAREN ; tableBuckets @init { msgs.push(""table buckets specification""); } @after { msgs.pop(); } : KW_CLUSTERED KW_BY LPAREN bucketCols=columnNameList RPAREN (KW_SORTED KW_BY LPAREN sortCols=columnNameOrderList RPAREN)? KW_INTO num=Number KW_BUCKETS ; tableSkewed @init { msgs.push(""table skewed specification""); } @after { msgs.pop(); } : KW_SKEWED KW_BY LPAREN skewedCols=columnNameList RPAREN KW_ON LPAREN (skewedValues=skewedValueElement) RPAREN (storedAsDirs)? ; rowFormat @init { msgs.push(""serde specification""); } @after { msgs.pop(); } : rowFormatSerde | rowFormatDelimited ; recordReader @init { msgs.push(""record reader specification""); } @after { msgs.pop(); } : KW_RECORDREADER StringLiteral ; recordWriter @init { msgs.push(""record writer specification""); } @after { msgs.pop(); } : KW_RECORDWRITER StringLiteral ; rowFormatSerde @init { msgs.push(""serde format specification""); } @after { msgs.pop(); } : KW_ROW KW_FORMAT KW_SERDE name=StringLiteral (KW_WITH KW_SERDEPROPERTIES serdeprops=tableProperties)? ; rowFormatDelimited @init { msgs.push(""serde properties specification""); } @after { msgs.pop(); } : KW_ROW KW_FORMAT KW_DELIMITED tableRowFormatFieldIdentifier? tableRowFormatCollItemsIdentifier? tableRowFormatMapKeysIdentifier? tableRowFormatLinesIdentifier? ; tableRowFormat @init { msgs.push(""table row format specification""); } @after { msgs.pop(); } : rowFormatDelimited | rowFormatSerde ; tablePropertiesPrefixed @init { msgs.push(""table properties with prefix""); } @after { msgs.pop(); } : KW_TBLPROPERTIES tableProperties ; tableProperties @init { msgs.push(""table properties""); } @after { msgs.pop(); } : LPAREN tablePropertiesList RPAREN ; tablePropertiesList @init { msgs.push(""table properties list""); } @after { msgs.pop(); } : keyValueProperty (COMMA keyValueProperty)* | keyProperty (COMMA keyProperty)* ; keyValueProperty @init { msgs.push(""specifying key/value property""); } @after { msgs.pop(); } : key=StringLiteral EQUAL value=StringLiteral ; keyProperty @init { msgs.push(""specifying key property""); } @after { msgs.pop(); } : key=StringLiteral ; tableRowFormatFieldIdentifier @init { msgs.push(""table row format's field separator""); } @after { msgs.pop(); } : KW_FIELDS KW_TERMINATED KW_BY fldIdnt=StringLiteral (KW_ESCAPED KW_BY fldEscape=StringLiteral)? ; tableRowFormatCollItemsIdentifier @init { msgs.push(""table row format's column separator""); } @after { msgs.pop(); } : KW_COLLECTION KW_ITEMS KW_TERMINATED KW_BY collIdnt=StringLiteral ; tableRowFormatMapKeysIdentifier @init { msgs.push(""table row format's map key separator""); } @after { msgs.pop(); } : KW_MAP KW_KEYS KW_TERMINATED KW_BY mapKeysIdnt=StringLiteral ; tableRowFormatLinesIdentifier @init { msgs.push(""table row format's line separator""); } @after { msgs.pop(); } : KW_LINES KW_TERMINATED KW_BY linesIdnt=StringLiteral ; tableFileFormat @init { msgs.push(""table file format specification""); } @after { msgs.pop(); } : KW_STORED KW_AS KW_SEQUENCEFILE | KW_STORED KW_AS KW_TEXTFILE | KW_STORED KW_AS KW_RCFILE | KW_STORED KW_AS KW_ORCFILE | KW_STORED KW_AS KW_INPUTFORMAT inFmt=StringLiteral KW_OUTPUTFORMAT outFmt=StringLiteral (KW_INPUTDRIVER inDriver=StringLiteral KW_OUTPUTDRIVER outDriver=StringLiteral)? | KW_STORED KW_BY storageHandler=StringLiteral (KW_WITH KW_SERDEPROPERTIES serdeprops=tableProperties)? | KW_STORED KW_AS genericSpec=identifier ; tableLocation @init { msgs.push(""table location specification""); } @after { msgs.pop(); } : KW_LOCATION locn=StringLiteral ; columnNameTypeList @init { msgs.push(""column name type list""); } @after { msgs.pop(); } : columnNameType (COMMA columnNameType)* ; columnNameColonTypeList @init { msgs.push(""column name type list""); } @after { msgs.pop(); } : columnNameColonType (COMMA columnNameColonType)* ; columnNameList @init { msgs.push(""column name list""); } @after { msgs.pop(); } : columnName (COMMA columnName)* ; columnName @init { msgs.push(""column name""); } @after { msgs.pop(); } : identifier ; columnNameOrderList @init { msgs.push(""column name order list""); } @after { msgs.pop(); } : columnNameOrder (COMMA columnNameOrder)* ; skewedValueElement @init { msgs.push(""skewed value element""); } @after { msgs.pop(); } : skewedColumnValues | skewedColumnValuePairList ; skewedColumnValuePairList @init { msgs.push(""column value pair list""); } @after { msgs.pop(); } : skewedColumnValuePair (COMMA skewedColumnValuePair)* ; skewedColumnValuePair @init { msgs.push(""column value pair""); } @after { msgs.pop(); } : LPAREN colValues=skewedColumnValues RPAREN ; skewedColumnValues @init { msgs.push(""column values""); } @after { msgs.pop(); } : skewedColumnValue (COMMA skewedColumnValue)* ; skewedColumnValue @init { msgs.push(""column value""); } @after { msgs.pop(); } : constant ; skewedValueLocationElement @init { msgs.push(""skewed value location element""); } @after { msgs.pop(); } : skewedColumnValue | skewedColumnValuePair ; columnNameOrder @init { msgs.push(""column name order""); } @after { msgs.pop(); } : identifier (asc=KW_ASC | desc=KW_DESC)? ; columnNameCommentList @init { msgs.push(""column name comment list""); } @after { msgs.pop(); } : columnNameComment (COMMA columnNameComment)* ; columnNameComment @init { msgs.push(""column name comment""); } @after { msgs.pop(); } : colName=identifier (KW_COMMENT comment=StringLiteral)? ; columnRefOrder @init { msgs.push(""column order""); } @after { msgs.pop(); } : expression (asc=KW_ASC | desc=KW_DESC)? ; columnNameType @init { msgs.push(""column specification""); } @after { msgs.pop(); } : colName=identifier colType (KW_COMMENT comment=StringLiteral)? ; columnNameColonType @init { msgs.push(""column specification""); } @after { msgs.pop(); } : colName=identifier COLON colType (KW_COMMENT comment=StringLiteral)? ; colType @init { msgs.push(""column type""); } @after { msgs.pop(); } : type ; colTypeList @init { msgs.push(""column type list""); } @after { msgs.pop(); } : colType (COMMA colType)* ; type : primitiveType | listType | structType | mapType | unionType; primitiveType @init { msgs.push(""primitive type specification""); } @after { msgs.pop(); } : KW_TINYINT | KW_SMALLINT | KW_INT | KW_BIGINT | KW_BOOLEAN | KW_FLOAT | KW_DOUBLE | KW_DATE | KW_DATETIME | KW_TIMESTAMP | KW_STRING | KW_BINARY | KW_DECIMAL ; listType @init { msgs.push(""list type""); } @after { msgs.pop(); } : KW_ARRAY LESSTHAN type GREATERTHAN ; structType @init { msgs.push(""struct type""); } @after { msgs.pop(); } : KW_STRUCT LESSTHAN columnNameColonTypeList GREATERTHAN ; mapType @init { msgs.push(""map type""); } @after { msgs.pop(); } : KW_MAP LESSTHAN left=primitiveType COMMA right=type GREATERTHAN ; unionType @init { msgs.push(""uniontype type""); } @after { msgs.pop(); } : KW_UNIONTYPE LESSTHAN colTypeList GREATERTHAN ; queryOperator @init { msgs.push(""query operator""); } @after { msgs.pop(); } : KW_UNION KW_ALL ; // select statement select ... from ... where ... group by ... order by ... queryStatementExpression : queryStatement (queryOperator queryStatement)* ; queryStatement : fromClause ( b+=body )+ | regular_body ; regular_body : insertClause selectClause fromClause whereClause? groupByClause? havingClause? orderByClause? clusterByClause? distributeByClause? sortByClause? window_clause? limitClause? | selectStatement ; selectStatement : selectClause fromClause whereClause? groupByClause? havingClause? orderByClause? clusterByClause? distributeByClause? sortByClause? window_clause? limitClause? ; body : insertClause selectClause whereClause? groupByClause? havingClause? orderByClause? clusterByClause? distributeByClause? sortByClause? window_clause? limitClause? | selectClause whereClause? groupByClause? havingClause? orderByClause? clusterByClause? distributeByClause? sortByClause? window_clause? limitClause? ; insertClause @init { msgs.push(""insert clause""); } @after { msgs.pop(); } : KW_INSERT KW_OVERWRITE destination ifNotExists? | KW_INSERT KW_INTO KW_TABLE tableOrPartition ; destination @init { msgs.push(""destination specification""); } @after { msgs.pop(); } : KW_LOCAL KW_DIRECTORY StringLiteral tableRowFormat? tableFileFormat? | KW_DIRECTORY StringLiteral | KW_TABLE tableOrPartition ; limitClause @init { msgs.push(""limit clause""); } @after { msgs.pop(); } : KW_LIMIT num=Number ; ",16203,True,3438.9186294903875,median "/** The MIT License (MIT) Copyright (c) 2016 by Dave Gandy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package flatspark.utils { public class AwesomeUtils { public function AwesomeUtils() { } public static const fa_500px:String = ""\\uf26e""; public static const fa_address_book:String = ""\\uf2b9""; public static const fa_address_book_o:String = ""\\uf2ba""; public static const fa_address_card:String = ""\\uf2bb""; public static const fa_address_card_o:String = ""\\uf2bc""; public static const fa_adjust:String = ""\\uf042""; public static const fa_adn:String = ""\\uf170""; public static const fa_align_center:String = ""\\uf037""; public static const fa_align_justify:String = ""\\uf039""; public static const fa_align_left:String = ""\\uf036""; public static const fa_align_right:String = ""\\uf038""; public static const fa_amazon:String = ""\\uf270""; public static const fa_ambulance:String = ""\\uf0f9""; public static const fa_american_sign_language_interpreting:String = ""\\uf2a3""; public static const fa_anchor:String = ""\\uf13d""; public static const fa_android:String = ""\\uf17b""; public static const fa_angellist:String = ""\\uf209""; public static const fa_angle_double_down:String = ""\\uf103""; public static const fa_angle_double_left:String = ""\\uf100""; public static const fa_angle_double_right:String = ""\\uf101""; public static const fa_angle_double_up:String = ""\\uf102""; public static const fa_angle_down:String = ""\\uf107""; public static const fa_angle_left:String = ""\\uf104""; public static const fa_angle_right:String = ""\\uf105""; public static const fa_angle_up:String = ""\\uf106""; public static const fa_apple:String = ""\\uf179""; public static const fa_archive:String = ""\\uf187""; public static const fa_area_chart:String = ""\\uf1fe""; public static const fa_arrow_circle_down:String = ""\\uf0ab""; public static const fa_arrow_circle_left:String = ""\\uf0a8""; public static const fa_arrow_circle_o_down:String = ""\\uf01a""; public static const fa_arrow_circle_o_left:String = ""\\uf190""; public static const fa_arrow_circle_o_right:String = ""\\uf18e""; public static const fa_arrow_circle_o_up:String = ""\\uf01b""; public static const fa_arrow_circle_right:String = ""\\uf0a9""; public static const fa_arrow_circle_up:String = ""\\uf0aa""; public static const fa_arrow_down:String = ""\\uf063""; public static const fa_arrow_left:String = ""\\uf060""; public static const fa_arrow_right:String = ""\\uf061""; public static const fa_arrow_up:String = ""\\uf062""; public static const fa_arrows:String = ""\\uf047""; public static const fa_arrows_alt:String = ""\\uf0b2""; public static const fa_arrows_h:String = ""\\uf07e""; public static const fa_arrows_v:String = ""\\uf07d""; public static const fa_asl_interpreting:String = ""\\uf2a3""; public static const fa_assistive_listening_systems:String = ""\\uf2a2""; public static const fa_asterisk:String = ""\\uf069""; public static const fa_at:String = ""\\uf1fa""; public static const fa_audio_description:String = ""\\uf29e""; public static const fa_automobile:String = ""\\uf1b9""; public static const fa_backward:String = ""\\uf04a""; public static const fa_balance_scale:String = ""\\uf24e""; public static const fa_ban:String = ""\\uf05e""; public static const fa_bandcamp:String = ""\\uf2d5""; public static const fa_bank:String = ""\\uf19c""; public static const fa_bar_chart:String = ""\\uf080""; public static const fa_bar_chart_o:String = ""\\uf080""; public static const fa_barcode:String = ""\\uf02a""; public static const fa_bars:String = ""\\uf0c9""; public static const fa_bath:String = ""\\uf2cd""; public static const fa_bathtub:String = ""\\uf2cd""; public static const fa_battery:String = ""\\uf240""; public static const fa_battery_0:String = ""\\uf244""; public static const fa_battery_1:String = ""\\uf243""; public static const fa_battery_2:String = ""\\uf242""; public static const fa_battery_3:String = ""\\uf241""; public static const fa_battery_4:String = ""\\uf240""; public static const fa_battery_empty:String = ""\\uf244""; public static const fa_battery_full:String = ""\\uf240""; public static const fa_battery_half:String = ""\\uf242""; public static const fa_battery_quarter:String = ""\\uf243""; public static const fa_battery_three_quarters:String = ""\\uf241""; public static const fa_bed:String = ""\\uf236""; public static const fa_beer:String = ""\\uf0fc""; public static const fa_behance:String = ""\\uf1b4""; public static const fa_behance_square:String = ""\\uf1b5""; public static const fa_bell:String = ""\\uf0f3""; public static const fa_bell_o:String = ""\\uf0a2""; public static const fa_bell_slash:String = ""\\uf1f6""; public static const fa_bell_slash_o:String = ""\\uf1f7""; public static const fa_bicycle:String = ""\\uf206""; public static const fa_binoculars:String = ""\\uf1e5""; public static const fa_birthday_cake:String = ""\\uf1fd""; public static const fa_bitbucket:String = ""\\uf171""; public static const fa_bitbucket_square:String = ""\\uf172""; public static const fa_bitcoin:String = ""\\uf15a""; public static const fa_black_tie:String = ""\\uf27e""; public static const fa_blind:String = ""\\uf29d""; public static const fa_bluetooth:String = ""\\uf293""; public static const fa_bluetooth_b:String = ""\\uf294""; public static const fa_bold:String = ""\\uf032""; public static const fa_bolt:String = ""\\uf0e7""; public static const fa_bomb:String = ""\\uf1e2""; public static const fa_book:String = ""\\uf02d""; public static const fa_bookmark:String = ""\\uf02e""; public static const fa_bookmark_o:String = ""\\uf097""; public static const fa_braille:String = ""\\uf2a1""; public static const fa_briefcase:String = ""\\uf0b1""; public static const fa_btc:String = ""\\uf15a""; public static const fa_bug:String = ""\\uf188""; public static const fa_building:String = ""\\uf1ad""; public static const fa_building_o:String = ""\\uf0f7""; public static const fa_bullhorn:String = ""\\uf0a1""; public static const fa_bullseye:String = ""\\uf140""; public static const fa_bus:String = ""\\uf207""; public static const fa_buysellads:String = ""\\uf20d""; public static const fa_cab:String = ""\\uf1ba""; public static const fa_calculator:String = ""\\uf1ec""; public static const fa_calendar:String = ""\\uf073""; public static const fa_calendar_check_o:String = ""\\uf274""; public static const fa_calendar_minus_o:String = ""\\uf272""; public static const fa_calendar_o:String = ""\\uf133""; public static const fa_calendar_plus_o:String = ""\\uf271""; public static const fa_calendar_times_o:String = ""\\uf273""; public static const fa_camera:String = ""\\uf030""; public static const fa_camera_retro:String = ""\\uf083""; public static const fa_car:String = ""\\uf1b9""; public static const fa_caret_down:String = ""\\uf0d7""; public static const fa_caret_left:String = ""\\uf0d9""; public static const fa_caret_right:String = ""\\uf0da""; public static const fa_caret_square_o_down:String = ""\\uf150""; public static const fa_caret_square_o_left:String = ""\\uf191""; public static const fa_caret_square_o_right:String = ""\\uf152""; public static const fa_caret_square_o_up:String = ""\\uf151""; public static const fa_caret_up:String = ""\\uf0d8""; public static const fa_cart_arrow_down:String = ""\\uf218""; public static const fa_cart_plus:String = ""\\uf217""; public static const fa_cc:String = ""\\uf20a""; public static const fa_cc_amex:String = ""\\uf1f3""; public static const fa_cc_diners_club:String = ""\\uf24c""; public static const fa_cc_discover:String = ""\\uf1f2""; public static const fa_cc_jcb:String = ""\\uf24b""; public static const fa_cc_mastercard:String = ""\\uf1f1""; public static const fa_cc_paypal:String = ""\\uf1f4""; public static const fa_cc_stripe:String = ""\\uf1f5""; public static const fa_cc_visa:String = ""\\uf1f0""; public static const fa_certificate:String = ""\\uf0a3""; public static const fa_chain:String = ""\\uf0c1""; public static const fa_chain_broken:String = ""\\uf127""; public static const fa_check:String = ""\\uf00c""; public static const fa_check_circle:String = ""\\uf058""; public static const fa_check_circle_o:String = ""\\uf05d""; public static const fa_check_square:String = ""\\uf14a""; public static const fa_check_square_o:String = ""\\uf046""; public static const fa_chevron_circle_down:String = ""\\uf13a""; public static const fa_chevron_circle_left:String = ""\\uf137""; public static const fa_chevron_circle_right:String = ""\\uf138""; public static const fa_chevron_circle_up:String = ""\\uf139""; public static const fa_chevron_down:String = ""\\uf078""; public static const fa_chevron_left:String = ""\\uf053""; public static const fa_chevron_right:String = ""\\uf054""; public static const fa_chevron_up:String = ""\\uf077""; public static const fa_child:String = ""\\uf1ae""; public static const fa_chrome:String = ""\\uf268""; public static const fa_circle:String = ""\\uf111""; public static const fa_circle_o:String = ""\\uf10c""; public static const fa_circle_o_notch:String = ""\\uf1ce""; public static const fa_circle_thin:String = ""\\uf1db""; public static const fa_clipboard:String = ""\\uf0ea""; public static const fa_clock_o:String = ""\\uf017""; public static const fa_clone:String = ""\\uf24d""; public static const fa_close:String = ""\\uf00d""; public static const fa_cloud:String = ""\\uf0c2""; public static const fa_cloud_download:String = ""\\uf0ed""; public static const fa_cloud_upload:String = ""\\uf0ee""; public static const fa_cny:String = ""\\uf157""; public static const fa_code:String = ""\\uf121""; public static const fa_code_fork:String = ""\\uf126""; public static const fa_codepen:String = ""\\uf1cb""; public static const fa_codiepie:String = ""\\uf284""; public static const fa_coffee:String = ""\\uf0f4""; public static const fa_cog:String = ""\\uf013""; public static const fa_cogs:String = ""\\uf085""; public static const fa_columns:String = ""\\uf0db""; public static const fa_comment:String = ""\\uf075""; public static const fa_comment_o:String = ""\\uf0e5""; public static const fa_commenting:String = ""\\uf27a""; public static const fa_commenting_o:String = ""\\uf27b""; public static const fa_comments:String = ""\\uf086""; public static const fa_comments_o:String = ""\\uf0e6""; public static const fa_compass:String = ""\\uf14e""; public static const fa_compress:String = ""\\uf066""; public static const fa_connectdevelop:String = ""\\uf20e""; public static const fa_contao:String = ""\\uf26d""; public static const fa_copy:String = ""\\uf0c5""; public static const fa_copyright:String = ""\\uf1f9""; public static const fa_creative_commons:String = ""\\uf25e""; public static const fa_credit_card:String = ""\\uf09d""; public static const fa_credit_card_alt:String = ""\\uf283""; public static const fa_crop:String = ""\\uf125""; public static const fa_crosshairs:String = ""\\uf05b""; public static const fa_css3:String = ""\\uf13c""; public static const fa_cube:String = ""\\uf1b2""; public static const fa_cubes:String = ""\\uf1b3""; public static const fa_cut:String = ""\\uf0c4""; public static const fa_cutlery:String = ""\\uf0f5""; public static const fa_dashboard:String = ""\\uf0e4""; public static const fa_dashcube:String = ""\\uf210""; public static const fa_database:String = ""\\uf1c0""; public static const fa_deaf:String = ""\\uf2a4""; public static const fa_deafness:String = ""\\uf2a4""; public static const fa_dedent:String = ""\\uf03b""; public static const fa_delicious:String = ""\\uf1a5""; public static const fa_desktop:String = ""\\uf108""; public static const fa_deviantart:String = ""\\uf1bd""; public static const fa_diamond:String = ""\\uf219""; public static const fa_digg:String = ""\\uf1a6""; public static const fa_dollar:String = ""\\uf155""; public static const fa_dot_circle_o:String = ""\\uf192""; public static const fa_download:String = ""\\uf019""; public static const fa_dribbble:String = ""\\uf17d""; public static const fa_drivers_license:String = ""\\uf2c2""; public static const fa_drivers_license_o:String = ""\\uf2c3""; public static const fa_dropbox:String = ""\\uf16b""; public static const fa_drupal:String = ""\\uf1a9""; public static const fa_edge:String = ""\\uf282""; public static const fa_edit:String = ""\\uf044""; public static const fa_eercast:String = ""\\uf2da""; public static const fa_eject:String = ""\\uf052""; public static const fa_ellipsis_h:String = ""\\uf141""; public static const fa_ellipsis_v:String = ""\\uf142""; public static const fa_empire:String = ""\\uf1d1""; public static const fa_envelope:String = ""\\uf0e0""; public static const fa_envelope_o:String = ""\\uf003""; public static const fa_envelope_open:String = ""\\uf2b6""; public static const fa_envelope_open_o:String = ""\\uf2b7""; public static const fa_envelope_square:String = ""\\uf199""; public static const fa_envira:String = ""\\uf299""; public static const fa_eraser:String = ""\\uf12d""; public static const fa_etsy:String = ""\\uf2d7""; public static const fa_eur:String = ""\\uf153""; public static const fa_euro:String = ""\\uf153""; public static const fa_exchange:String = ""\\uf0ec""; public static const fa_exclamation:String = ""\\uf12a""; public static const fa_exclamation_circle:String = ""\\uf06a""; public static const fa_exclamation_triangle:String = ""\\uf071""; public static const fa_expand:String = ""\\uf065""; public static const fa_expeditedssl:String = ""\\uf23e""; public static const fa_external_link:String = ""\\uf08e""; public static const fa_external_link_square:String = ""\\uf14c""; public static const fa_eye:String = ""\\uf06e""; public static const fa_eye_slash:String = ""\\uf070""; public static const fa_eyedropper:String = ""\\uf1fb""; public static const fa_fa:String = ""\\uf2b4""; public static const fa_facebook:String = ""\\uf09a""; public static const fa_facebook_f:String = ""\\uf09a""; public static const fa_facebook_official:String = ""\\uf230""; public static const fa_facebook_square:String = ""\\uf082""; public static const fa_fast_backward:String = ""\\uf049""; public static const fa_fast_forward:String = ""\\uf050""; public static const fa_fax:String = ""\\uf1ac""; public static const fa_feed:String = ""\\uf09e""; public static const fa_female:String = ""\\uf182""; public static const fa_fighter_jet:String = ""\\uf0fb""; public static const fa_file:String = ""\\uf15b""; public static const fa_file_archive_o:String = ""\\uf1c6""; public static const fa_file_audio_o:String = ""\\uf1c7""; public static const fa_file_code_o:String = ""\\uf1c9""; public static const fa_file_excel_o:String = ""\\uf1c3""; public static const fa_file_image_o:String = ""\\uf1c5""; public static const fa_file_movie_o:String = ""\\uf1c8""; public static const fa_file_o:String = ""\\uf016""; public static const fa_file_pdf_o:String = ""\\uf1c1""; public static const fa_file_photo_o:String = ""\\uf1c5""; public static const fa_file_picture_o:String = ""\\uf1c5""; public static const fa_file_powerpoint_o:String = ""\\uf1c4""; public static const fa_file_sound_o:String = ""\\uf1c7""; public static const fa_file_text:String = ""\\uf15c""; public static const fa_file_text_o:String = ""\\uf0f6""; public static const fa_file_video_o:String = ""\\uf1c8""; public static const fa_file_word_o:String = ""\\uf1c2""; public static const fa_file_zip_o:String = ""\\uf1c6""; public static const fa_files_o:String = ""\\uf0c5""; public static const fa_film:String = ""\\uf008""; public static const fa_filter:String = ""\\uf0b0""; public static const fa_fire:String = ""\\uf06d""; public static const fa_fire_extinguisher:String = ""\\uf134""; public static const fa_firefox:String = ""\\uf269""; public static const fa_first_order:String = ""\\uf2b0""; public static const fa_flag:String = ""\\uf024""; public static const fa_flag_checkered:String = ""\\uf11e""; public static const fa_flag_o:String = ""\\uf11d""; public static const fa_flash:String = ""\\uf0e7""; public static const fa_flask:String = ""\\uf0c3""; public static const fa_flickr:String = ""\\uf16e""; public static const fa_floppy_o:String = ""\\uf0c7""; public static const fa_folder:String = ""\\uf07b""; public static const fa_folder_o:String = ""\\uf114""; public static const fa_folder_open:String = ""\\uf07c""; public static const fa_folder_open_o:String = ""\\uf115""; public static const fa_font:String = ""\\uf031""; public static const fa_font_awesome:String = ""\\uf2b4""; public static const fa_fonticons:String = ""\\uf280""; public static const fa_fort_awesome:String = ""\\uf286""; public static const fa_forumbee:String = ""\\uf211""; public static const fa_forward:String = ""\\uf04e""; public static const fa_foursquare:String = ""\\uf180""; public static const fa_free_code_camp:String = ""\\uf2c5""; public static const fa_frown_o:String = ""\\uf119""; public static const fa_futbol_o:String = ""\\uf1e3""; public static const fa_gamepad:String = ""\\uf11b""; public static const fa_gavel:String = ""\\uf0e3""; public static const fa_gbp:String = ""\\uf154""; public static const fa_ge:String = ""\\uf1d1""; public static const fa_gear:String = ""\\uf013""; public static const fa_gears:String = ""\\uf085""; public static const fa_genderless:String = ""\\uf22d""; public static const fa_get_pocket:String = ""\\uf265""; public static const fa_gg:String = ""\\uf260""; public static const fa_gg_circle:String = ""\\uf261""; public static const fa_gift:String = ""\\uf06b""; public static const fa_git:String = ""\\uf1d3""; public static const fa_git_square:String = ""\\uf1d2""; public static const fa_github:String = ""\\uf09b""; public static const fa_github_alt:String = ""\\uf113""; public static const fa_github_square:String = ""\\uf092""; public static const fa_gitlab:String = ""\\uf296""; public static const fa_gittip:String = ""\\uf184""; public static const fa_glass:String = ""\\uf000""; public static const fa_glide:String = ""\\uf2a5""; public static const fa_glide_g:String = ""\\uf2a6""; public static const fa_globe:String = ""\\uf0ac""; public static const fa_google:String = ""\\uf1a0""; public static const fa_google_plus:String = ""\\uf0d5""; public static const fa_google_plus_circle:String = ""\\uf2b3""; public static const fa_google_plus_official:String = ""\\uf2b3""; public static const fa_google_plus_square:String = ""\\uf0d4""; public static const fa_google_wallet:String = ""\\uf1ee""; public static const fa_graduation_cap:String = ""\\uf19d""; public static const fa_gratipay:String = ""\\uf184""; public static const fa_grav:String = ""\\uf2d6""; public static const fa_group:String = ""\\uf0c0""; public static const fa_h_square:String = ""\\uf0fd""; public static const fa_hacker_news:String = ""\\uf1d4""; public static const fa_hand_grab_o:String = ""\\uf255""; public static const fa_hand_lizard_o:String = ""\\uf258""; public static const fa_hand_o_down:String = ""\\uf0a7""; public static const fa_hand_o_left:String = ""\\uf0a5""; public static const fa_hand_o_right:String = ""\\uf0a4""; public static const fa_hand_o_up:String = ""\\uf0a6""; public static const fa_hand_paper_o:String = ""\\uf256""; public static const fa_hand_peace_o:String = ""\\uf25b""; public static const fa_hand_pointer_o:String = ""\\uf25a""; public static const fa_hand_rock_o:String = ""\\uf255""; public static const fa_hand_scissors_o:String = ""\\uf257""; public static const fa_hand_spock_o:String = ""\\uf259""; public static const fa_hand_stop_o:String = ""\\uf256""; public static const fa_handshake_o:String = ""\\uf2b5""; public static const fa_hard_of_hearing:String = ""\\uf2a4""; public static const fa_hashtag:String = ""\\uf292""; public static const fa_hdd_o:String = ""\\uf0a0""; public static const fa_header:String = ""\\uf1dc""; public static const fa_headphones:String = ""\\uf025""; public static const fa_heart:String = ""\\uf004""; public static const fa_heart_o:String = ""\\uf08a""; public static const fa_heartbeat:String = ""\\uf21e""; public static const fa_history:String = ""\\uf1da""; public static const fa_home:String = ""\\uf015""; public static const fa_hospital_o:String = ""\\uf0f8""; public static const fa_hotel:String = ""\\uf236""; public static const fa_hourglass:String = ""\\uf254""; public static const fa_hourglass_1:String = ""\\uf251""; public static const fa_hourglass_2:String = ""\\uf252""; public static const fa_hourglass_3:String = ""\\uf253""; public static const fa_hourglass_end:String = ""\\uf253""; public static const fa_hourglass_half:String = ""\\uf252""; public static const fa_hourglass_o:String = ""\\uf250""; public static const fa_hourglass_start:String = ""\\uf251""; public static const fa_houzz:String = ""\\uf27c""; public static const fa_html5:String = ""\\uf13b""; public static const fa_i_cursor:String = ""\\uf246""; public static const fa_id_badge:String = ""\\uf2c1""; public static const fa_id_card:String = ""\\uf2c2""; public static const fa_id_card_o:String = ""\\uf2c3""; public static const fa_ils:String = ""\\uf20b""; public static const fa_image:String = ""\\uf03e""; public static const fa_imdb:String = ""\\uf2d8""; public static const fa_inbox:String = ""\\uf01c""; public static const fa_indent:String = ""\\uf03c""; public static const fa_industry:String = ""\\uf275""; public static const fa_info:String = ""\\uf129""; public static const fa_info_circle:String = ""\\uf05a""; public static const fa_inr:String = ""\\uf156""; public static const fa_instagram:String = ""\\uf16d""; public static const fa_institution:String = ""\\uf19c""; public static const fa_internet_explorer:String = ""\\uf26b""; public static const fa_intersex:String = ""\\uf224""; public static const fa_ioxhost:String = ""\\uf208""; public static const fa_italic:String = ""\\uf033""; public static const fa_joomla:String = ""\\uf1aa""; public static const fa_jpy:String = ""\\uf157""; public static const fa_jsfiddle:String = ""\\uf1cc""; public static const fa_key:String = ""\\uf084""; public static const fa_keyboard_o:String = ""\\uf11c""; public static const fa_krw:String = ""\\uf159""; public static const fa_language:String = ""\\uf1ab""; public static const fa_laptop:String = ""\\uf109""; public static const fa_lastfm:String = ""\\uf202""; public static const fa_lastfm_square:String = ""\\uf203""; public static const fa_leaf:String = ""\\uf06c""; public static const fa_leanpub:String = ""\\uf212""; public static const fa_legal:String = ""\\uf0e3""; public static const fa_lemon_o:String = ""\\uf094""; public static const fa_level_down:String = ""\\uf149""; public static const fa_level_up:String = ""\\uf148""; public static const fa_life_bouy:String = ""\\uf1cd""; public static const fa_life_buoy:String = ""\\uf1cd""; public static const fa_life_ring:String = ""\\uf1cd""; public static const fa_life_saver:String = ""\\uf1cd""; public static const fa_lightbulb_o:String = ""\\uf0eb""; public static const fa_line_chart:String = ""\\uf201""; public static const fa_link:String = ""\\uf0c1""; public static const fa_linkedin:String = ""\\uf0e1""; public static const fa_linkedin_square:String = ""\\uf08c""; public static const fa_linode:String = ""\\uf2b8""; public static const fa_linux:String = ""\\uf17c""; public static const fa_list:String = ""\\uf03a""; public static const fa_list_alt:String = ""\\uf022""; public static const fa_list_ol:String = ""\\uf0cb""; public static const fa_list_ul:String = ""\\uf0ca""; public static const fa_location_arrow:String = ""\\uf124""; public static const fa_lock:String = ""\\uf023""; public static const fa_long_arrow_down:String = ""\\uf175""; public static const fa_long_arrow_left:String = ""\\uf177""; public static const fa_long_arrow_right:String = ""\\uf178""; public static const fa_long_arrow_up:String = ""\\uf176""; public static const fa_low_vision:String = ""\\uf2a8""; public static const fa_magic:String = ""\\uf0d0""; public static const fa_magnet:String = ""\\uf076""; public static const fa_mail_forward:String = ""\\uf064""; public static const fa_mail_reply:String = ""\\uf112""; public static const fa_mail_reply_all:String = ""\\uf122""; public static const fa_male:String = ""\\uf183""; public static const fa_map:String = ""\\uf279""; public static const fa_map_marker:String = ""\\uf041""; public static const fa_map_o:String = ""\\uf278""; public static const fa_map_pin:String = ""\\uf276""; public static const fa_map_signs:String = ""\\uf277""; public static const fa_mars:String = ""\\uf222""; public static const fa_mars_double:String = ""\\uf227""; public static const fa_mars_stroke:String = ""\\uf229""; public static const fa_mars_stroke_h:String = ""\\uf22b""; public static const fa_mars_stroke_v:String = ""\\uf22a""; public static const fa_maxcdn:String = ""\\uf136""; public static const fa_meanpath:String = ""\\uf20c""; public static const fa_medium:String = ""\\uf23a""; public static const fa_medkit:String = ""\\uf0fa""; public static const fa_meetup:String = ""\\uf2e0""; public static const fa_meh_o:String = ""\\uf11a""; public static const fa_mercury:String = ""\\uf223""; public static const fa_microchip:String = ""\\uf2db""; public static const fa_microphone:String = ""\\uf130""; public static const fa_microphone_slash:String = ""\\uf131""; public static const fa_minus:String = ""\\uf068""; public static const fa_minus_circle:String = ""\\uf056""; public static const fa_minus_square:String = ""\\uf146""; public static const fa_minus_square_o:String = ""\\uf147""; public static const fa_mixcloud:String = ""\\uf289""; public static const fa_mobile:String = ""\\uf10b""; public static const fa_mobile_phone:String = ""\\uf10b""; public static const fa_modx:String = ""\\uf285""; public static const fa_money:String = ""\\uf0d6""; public static const fa_moon_o:String = ""\\uf186""; public static const fa_mortar_board:String = ""\\uf19d""; public static const fa_motorcycle:String = ""\\uf21c""; public static const fa_mouse_pointer:String = ""\\uf245""; public static const fa_music:String = ""\\uf001""; public static const fa_navicon:String = ""\\uf0c9""; public static const fa_neuter:String = ""\\uf22c""; public static const fa_newspaper_o:String = ""\\uf1ea""; public static const fa_object_group:String = ""\\uf247""; public static const fa_object_ungroup:String = ""\\uf248""; public static const fa_odnoklassniki:String = ""\\uf263""; public static const fa_odnoklassniki_square:String = ""\\uf264""; public static const fa_opencart:String = ""\\uf23d""; public static const fa_openid:String = ""\\uf19b""; public static const fa_opera:String = ""\\uf26a""; public static const fa_optin_monster:String = ""\\uf23c""; public static const fa_outdent:String = ""\\uf03b""; public static const fa_pagelines:String = ""\\uf18c""; public static const fa_paint_brush:String = ""\\uf1fc""; public static const fa_paper_plane:String = ""\\uf1d8""; public static const fa_paper_plane_o:String = ""\\uf1d9""; public static const fa_paperclip:String = ""\\uf0c6""; public static const fa_paragraph:String = ""\\uf1dd""; public static const fa_paste:String = ""\\uf0ea""; public static const fa_pause:String = ""\\uf04c""; public static const fa_pause_circle:String = ""\\uf28b""; public static const fa_pause_circle_o:String = ""\\uf28c""; public static const fa_paw:String = ""\\uf1b0""; public static const fa_paypal:String = ""\\uf1ed""; public static const fa_pencil:String = ""\\uf040""; public static const fa_pencil_square:String = ""\\uf14b""; public static const fa_pencil_square_o:String = ""\\uf044""; public static const fa_percent:String = ""\\uf295""; public static const fa_phone:String = ""\\uf095""; public static const fa_phone_square:String = ""\\uf098""; public static const fa_photo:String = ""\\uf03e""; public static const fa_picture_o:String = ""\\uf03e""; public static const fa_pie_chart:String = ""\\uf200""; public static const fa_pied_piper:String = ""\\uf2ae""; public static const fa_pied_piper_alt:String = ""\\uf1a8""; public static const fa_pied_piper_pp:String = ""\\uf1a7""; public static const fa_pinterest:String = ""\\uf0d2""; public static const fa_pinterest_p:String = ""\\uf231""; public static const fa_pinterest_square:String = ""\\uf0d3""; public static const fa_plane:String = ""\\uf072""; public static const fa_play:String = ""\\uf04b""; public static const fa_play_circle:String = ""\\uf144""; public static const fa_play_circle_o:String = ""\\uf01d""; public static const fa_plug:String = ""\\uf1e6""; public static const fa_plus:String = ""\\uf067""; public static const fa_plus_circle:String = ""\\uf055""; public static const fa_plus_square:String = ""\\uf0fe""; public static const fa_plus_square_o:String = ""\\uf196""; public static const fa_podcast:String = ""\\uf2ce""; public static const fa_power_off:String = ""\\uf011""; public static const fa_print:String = ""\\uf02f""; public static const fa_product_hunt:String = ""\\uf288""; public static const fa_puzzle_piece:String = ""\\uf12e""; public static const fa_qq:String = ""\\uf1d6""; public static const fa_qrcode:String = ""\\uf029""; public static const fa_question:String = ""\\uf128""; public static const fa_question_circle:String = ""\\uf059""; public static const fa_question_circle_o:String = ""\\uf29c""; public static const fa_quora:String = ""\\uf2c4""; public static const fa_quote_left:String = ""\\uf10d""; public static const fa_quote_right:String = ""\\uf10e""; public static const fa_ra:String = ""\\uf1d0""; public static const fa_random:String = ""\\uf074""; public static const fa_ravelry:String = ""\\uf2d9""; public static const fa_rebel:String = ""\\uf1d0""; public static const fa_recycle:String = ""\\uf1b8""; public static const fa_reddit:String = ""\\uf1a1""; public static const fa_reddit_alien:String = ""\\uf281""; public static const fa_reddit_square:String = ""\\uf1a2""; public static const fa_refresh:String = ""\\uf021""; public static const fa_registered:String = ""\\uf25d""; public static const fa_remove:String = ""\\uf00d""; public static const fa_renren:String = ""\\uf18b""; public static const fa_reorder:String = ""\\uf0c9""; public static const fa_repeat:String = ""\\uf01e""; public static const fa_reply:String = ""\\uf112""; public static const fa_reply_all:String = ""\\uf122""; public static const fa_resistance:String = ""\\uf1d0""; public static const fa_retweet:String = ""\\uf079""; public static const fa_rmb:String = ""\\uf157""; public static const fa_road:String = ""\\uf018""; public static const fa_rocket:String = ""\\uf135""; public static const fa_rotate_left:String = ""\\uf0e2""; public static const fa_rotate_right:String = ""\\uf01e""; public static const fa_rouble:String = ""\\uf158""; public static const fa_rss:String = ""\\uf09e""; public static const fa_rss_square:String = ""\\uf143""; public static const fa_rub:String = ""\\uf158""; public static const fa_ruble:String = ""\\uf158""; public static const fa_rupee:String = ""\\uf156""; public static const fa_s15:String = ""\\uf2cd""; public static const fa_safari:String = ""\\uf267""; public static const fa_save:String = ""\\uf0c7""; public static const fa_scissors:String = ""\\uf0c4""; public static const fa_scribd:String = ""\\uf28a""; public static const fa_search:String = ""\\uf002""; public static const fa_search_minus:String = ""\\uf010""; public static const fa_search_plus:String = ""\\uf00e""; public static const fa_sellsy:String = ""\\uf213""; public static const fa_send:String = ""\\uf1d8""; public static const fa_send_o:String = ""\\uf1d9""; public static const fa_server:String = ""\\uf233""; public static const fa_share:String = ""\\uf064""; public static const fa_share_alt:String = ""\\uf1e0""; public static const fa_share_alt_square:String = ""\\uf1e1""; public static const fa_share_square:String = ""\\uf14d""; public static const fa_share_square_o:String = ""\\uf045""; public static const fa_shekel:String = ""\\uf20b""; public static const fa_sheqel:String = ""\\uf20b""; public static const fa_shield:String = ""\\uf132""; public static const fa_ship:String = ""\\uf21a""; public static const fa_shirtsinbulk:String = ""\\uf214""; public static const fa_shopping_bag:String = ""\\uf290""; public static const fa_shopping_basket:String = ""\\uf291""; public static const fa_shopping_cart:String = ""\\uf07a""; public static const fa_shower:String = ""\\uf2cc""; public static const fa_sign_in:String = ""\\uf090""; public static const fa_sign_language:String = ""\\uf2a7""; public static const fa_sign_out:String = ""\\uf08b""; public static const fa_signal:String = ""\\uf012""; public static const fa_signing:String = ""\\uf2a7""; public static const fa_simplybuilt:String = ""\\uf215""; public static const fa_sitemap:String = ""\\uf0e8""; public static const fa_skyatlas:String = ""\\uf216""; public static const fa_skype:String = ""\\uf17e""; public static const fa_slack:String = ""\\uf198""; public static const fa_sliders:String = ""\\uf1de""; public static const fa_slideshare:String = ""\\uf1e7""; public static const fa_smile_o:String = ""\\uf118""; public static const fa_snapchat:String = ""\\uf2ab""; public static const fa_snapchat_ghost:String = ""\\uf2ac""; public static const fa_snapchat_square:String = ""\\uf2ad""; public static const fa_snowflake_o:String = ""\\uf2dc""; public static const fa_soccer_ball_o:String = ""\\uf1e3""; public static const fa_sort:String = ""\\uf0dc""; public static const fa_sort_alpha_asc:String = ""\\uf15d""; public static const fa_sort_alpha_desc:String = ""\\uf15e""; public static const fa_sort_amount_asc:String = ""\\uf160""; public static const fa_sort_amount_desc:String = ""\\uf161""; public static const fa_sort_asc:String = ""\\uf0de""; public static const fa_sort_desc:String = ""\\uf0dd""; public static const fa_sort_down:String = ""\\uf0dd""; public static const fa_sort_numeric_asc:String = ""\\uf162""; public static const fa_sort_numeric_desc:String = ""\\uf163""; public static const fa_sort_up:String = ""\\uf0de""; public static const fa_soundcloud:String = ""\\uf1be""; public static const fa_space_shuttle:String = ""\\uf197""; public static const fa_spinner:String = ""\\uf110""; public static const fa_spoon:String = ""\\uf1b1""; public static const fa_spotify:String = ""\\uf1bc""; public static const fa_square:String = ""\\uf0c8""; public static const fa_square_o:String = ""\\uf096""; public static const fa_stack_exchange:String = ""\\uf18d""; public static const fa_stack_overflow:String = ""\\uf16c""; public static const fa_star:String = ""\\uf005""; public static const fa_star_half:String = ""\\uf089""; public static const fa_star_half_empty:String = ""\\uf123""; public static const fa_star_half_full:String = ""\\uf123""; public static const fa_star_half_o:String = ""\\uf123""; public static const fa_star_o:String = ""\\uf006""; public static const fa_steam:String = ""\\uf1b6""; public static const fa_steam_square:String = ""\\uf1b7""; public static const fa_step_backward:String = ""\\uf048""; public static const fa_step_forward:String = ""\\uf051""; public static const fa_stethoscope:String = ""\\uf0f1""; public static const fa_sticky_note:String = ""\\uf249""; public static const fa_sticky_note_o:String = ""\\uf24a""; public static const fa_stop:String = ""\\uf04d""; public static const fa_stop_circle:String = ""\\uf28d""; public static const fa_stop_circle_o:String = ""\\uf28e""; public static const fa_street_view:String = ""\\uf21d""; public static const fa_strikethrough:String = ""\\uf0cc""; public static const fa_stumbleupon:String = ""\\uf1a4""; public static const fa_stumbleupon_circle:String = ""\\uf1a3""; public static const fa_subscript:String = ""\\uf12c""; public static const fa_subway:String = ""\\uf239""; public static const fa_suitcase:String = ""\\uf0f2""; public static const fa_sun_o:String = ""\\uf185""; public static const fa_superpowers:String = ""\\uf2dd""; public static const fa_superscript:String = ""\\uf12b""; public static const fa_support:String = ""\\uf1cd""; public static const fa_table:String = ""\\uf0ce""; public static const fa_tablet:String = ""\\uf10a""; public static const fa_tachometer:String = ""\\uf0e4""; public static const fa_tag:String = ""\\uf02b""; public static const fa_tags:String = ""\\uf02c""; public static const fa_tasks:String = ""\\uf0ae""; public static const fa_taxi:String = ""\\uf1ba""; public static const fa_telegram:String = ""\\uf2c6""; public static const fa_television:String = ""\\uf26c""; public static const fa_tencent_weibo:String = ""\\uf1d5""; public static const fa_terminal:String = ""\\uf120""; public static const fa_text_height:String = ""\\uf034""; public static const fa_text_width:String = ""\\uf035""; public static const fa_th:String = ""\\uf00a""; public static const fa_th_large:String = ""\\uf009""; public static const fa_th_list:String = ""\\uf00b""; public static const fa_themeisle:String = ""\\uf2b2""; public static const fa_thermometer:String = ""\\uf2c7""; public static const fa_thermometer_0:String = ""\\uf2cb""; public static const fa_thermometer_1:String = ""\\uf2ca""; public static const fa_thermometer_2:String = ""\\uf2c9""; public static const fa_thermometer_3:String = ""\\uf2c8""; public static const fa_thermometer_4:String = ""\\uf2c7""; public static const fa_thermometer_empty:String = ""\\uf2cb""; public static const fa_thermometer_full:String = ""\\uf2c7""; public static const fa_thermometer_half:String = ""\\uf2c9""; public static const fa_thermometer_quarter:String = ""\\uf2ca""; public static const fa_thermometer_three_quarters:String = ""\\uf2c8""; public static const fa_thumb_tack:String = ""\\uf08d""; public static const fa_thumbs_down:String = ""\\uf165""; public static const fa_thumbs_o_down:String = ""\\uf088""; public static const fa_thumbs_o_up:String = ""\\uf087""; public static const fa_thumbs_up:String = ""\\uf164""; public static const fa_ticket:String = ""\\uf145""; public static const fa_times:String = ""\\uf00d""; public static const fa_times_circle:String = ""\\uf057""; public static const fa_times_circle_o:String = ""\\uf05c""; public static const fa_times_rectangle:String = ""\\uf2d3""; public static const fa_times_rectangle_o:String = ""\\uf2d4""; public static const fa_tint:String = ""\\uf043""; public static const fa_toggle_down:String = ""\\uf150""; public static const fa_toggle_left:String = ""\\uf191""; public static const fa_toggle_off:String = ""\\uf204""; public static const fa_toggle_on:String = ""\\uf205""; public static const fa_toggle_right:String = ""\\uf152""; public static const fa_toggle_up:String = ""\\uf151""; public static const fa_trademark:String = ""\\uf25c""; public static const fa_train:String = ""\\uf238""; public static const fa_transgender:String = ""\\uf224""; public static const fa_transgender_alt:String = ""\\uf225""; public static const fa_trash:String = ""\\uf1f8""; public static const fa_trash_o:String = ""\\uf014""; public static const fa_tree:String = ""\\uf1bb""; public static const fa_trello:String = ""\\uf181""; public static const fa_tripadvisor:String = ""\\uf262""; public static const fa_trophy:String = ""\\uf091""; public static const fa_truck:String = ""\\uf0d1""; public static const fa_try:String = ""\\uf195""; public static const fa_tty:String = ""\\uf1e4""; public static const fa_tumblr:String = ""\\uf173""; public static const fa_tumblr_square:String = ""\\uf174""; public static const fa_turkish_lira:String = ""\\uf195""; public static const fa_tv:String = ""\\uf26c""; public static const fa_twitch:String = ""\\uf1e8""; public static const fa_twitter:String = ""\\uf099""; public static const fa_twitter_square:String = ""\\uf081""; public static const fa_umbrella:String = ""\\uf0e9""; public static const fa_underline:String = ""\\uf0cd""; public static const fa_undo:String = ""\\uf0e2""; public static const fa_universal_access:String = ""\\uf29a""; public static const fa_university:String = ""\\uf19c""; public static const fa_unlink:String = ""\\uf127""; public static const fa_unlock:String = ""\\uf09c""; public static const fa_unlock_alt:String = ""\\uf13e""; public static const fa_unsorted:String = ""\\uf0dc""; public static const fa_upload:String = ""\\uf093""; public static const fa_usb:String = ""\\uf287""; public static const fa_usd:String = ""\\uf155""; public static const fa_user:String = ""\\uf007""; public static const fa_user_circle:String = ""\\uf2bd""; public static const fa_user_circle_o:String = ""\\uf2be""; public static const fa_user_md:String = ""\\uf0f0""; public static const fa_user_o:String = ""\\uf2c0""; public static const fa_user_plus:String = ""\\uf234""; public static const fa_user_secret:String = ""\\uf21b""; public static const fa_user_times:String = ""\\uf235""; public static const fa_users:String = ""\\uf0c0""; public static const fa_vcard:String = ""\\uf2bb""; public static const fa_vcard_o:String = ""\\uf2bc""; public static const fa_venus:String = ""\\uf221""; public static const fa_venus_double:String = ""\\uf226""; public static const fa_venus_mars:String = ""\\uf228""; public static const fa_viacoin:String = ""\\uf237""; public static const fa_viadeo:String = ""\\uf2a9""; public static const fa_viadeo_square:String = ""\\uf2aa""; public static const fa_video_camera:String = ""\\uf03d""; public static const fa_vimeo:String = ""\\uf27d""; public static const fa_vimeo_square:String = ""\\uf194""; public static const fa_vine:String = ""\\uf1ca""; public static const fa_vk:String = ""\\uf189""; public static const fa_volume_control_phone:String = ""\\uf2a0""; public static const fa_volume_down:String = ""\\uf027""; public static const fa_volume_off:String = ""\\uf026""; public static const fa_volume_up:String = ""\\uf028""; public static const fa_warning:String = ""\\uf071""; public static const fa_wechat:String = ""\\uf1d7""; public static const fa_weibo:String = ""\\uf18a""; public static const fa_weixin:String = ""\\uf1d7""; public static const fa_whatsapp:String = ""\\uf232""; public static const fa_wheelchair:String = ""\\uf193""; public static const fa_wheelchair_alt:String = ""\\uf29b""; public static const fa_wifi:String = ""\\uf1eb""; public static const fa_wikipedia_w:String = ""\\uf266""; public static const fa_window_close:String = ""\\uf2d3""; public static const fa_window_close_o:String = ""\\uf2d4""; public static const fa_window_maximize:String = ""\\uf2d0""; public static const fa_window_minimize:String = ""\\uf2d1""; public static const fa_window_restore:String = ""\\uf2d2""; public static const fa_windows:String = ""\\uf17a""; public static const fa_won:String = ""\\uf159""; public static const fa_wordpress:String = ""\\uf19a""; public static const fa_wpbeginner:String = ""\\uf297""; public static const fa_wpexplorer:String = ""\\uf2de""; public static const fa_wpforms:String = ""\\uf298""; public static const fa_wrench:String = ""\\uf0ad""; public static const fa_xing:String = ""\\uf168""; public static const fa_xing_square:String = ""\\uf169""; public static const fa_y_combinator:String = ""\\uf23b""; public static const fa_y_combinator_square:String = ""\\uf1d4""; public static const fa_yahoo:String = ""\\uf19e""; public static const fa_yc:String = ""\\uf23b""; public static const fa_yc_square:String = ""\\uf1d4""; public static const fa_yelp:String = ""\\uf1e9""; public static const fa_yen:String = ""\\uf157""; public static const fa_yoast:String = ""\\uf2b1""; public static const fa_youtube:String = ""\\uf167""; public static const fa_youtube_play:String = ""\\uf16a""; public static const fa_youtube_square:String = ""\\uf166""; } }",12282,True,3832.5960389765864,median "grammar AsylumClean; /* To Do List: * Embedded Functions * Macros? Notes: * Tuple expressions that return void are ignored (comma operator). */ // Indent stuff. tokens { INDENT, DEDENT } @lexer::header { import com.yuvalshavit.antlr4.DenterHelper; } @lexer::members { private final DenterHelper denter = new DenterHelper(NL, AsylumCleanParser.INDENT, AsylumCleanParser.DEDENT) { @Override public Token pullToken() { return AsylumCleanLexer.super.nextToken(); } }; @Override public Token nextToken() { return denter.nextToken(); } } // Entry point. init : universal_statement* ; // Universal statement. universal_statement : using_statement #UniversalUsing | namespace_statement #UniversalNamespace | extern_function_definition #UniversalExternFunction | function_definition #UniversalFunction | enum_definition #UniversalEnum | union_definition #UniversalUnion | struct_definition #UniversalStruct | interface_definition #UniversalInterface | implementation_definition #UniversalImplementation | typedef_definition #UniversalTypedef | code_statement #UniversalTopLevelCode ; // Using statement. using_statement : USING STATIC? IDENTIFIER ('.' IDENTIFIER)* ('.*')? NL ; // Namespace statement. namespace_statement : NAMESPACE IDENTIFIER ('.' IDENTIFIER)* NL ; // Extern function property. extern_function_property : STATIC | ASYNC ; // Extern function definition. extern_function_definition : attribute* EXTERN access_modifier? extern_function_property* FUNCTION IDENTIFIER '(' variable_arguments ')' (OP_RET variable_type)? NL ; // Function property. function_property : STATIC | INLINE | ASYNC | UNSAFE ; // Function definition. function_definition : attribute* access_modifier? function_property* FUNCTION IDENTIFIER generic_definition? '(' variable_arguments ')' (OP_RET variable_type)? (OP_LAMBDA expression | INDENT code_statement+ DEDENT | NL)? ; // Construction definition. constructor_definition : attribute* access_modifier? function_property* variable_type generic_definition? '(' variable_arguments ')' ((OP_LAMBDA expression NL | INDENT code_statement+ DEDENT) | NL) ; // Operator overloading. operator_definition : attribute* INLINE? OPERATOR operator '(' variable_arguments ')' (OP_RET variable_type)? ((OP_LAMBDA expression NL | INDENT code_statement+ DEDENT) | NL) ; // Attribute. attribute : '[' IDENTIFIER ('(' expression (',' expression)* ')')? ']' NL ; // Enum declaration. enum_definition : attribute* access_modifier? ENUM IDENTIFIER (':' INTEGER)? (INDENT enum_entry+ DEDENT)? ; // Enum entry. enum_entry : IDENTIFIER (ASSIGN_OP_EQ INTEGER)? NL #EnumEntryPlain | IDENTIFIER '(' (variable_type (',' variable_type)*)? ')' (ASSIGN_OP_EQ INTEGER)? NL #EnumEntryData | IDENTIFIER (ASSIGN_OP_EQ INTEGER)? INDENT (variable_parameter NL)+ DEDENT #EnumEntryStructs ; // Union declaration. union_definition : attribute* UNSAFE access_modifier? UNION IDENTIFIER INDENT (variable_parameter NL+)+ DEDENT ; // Struct declaration. struct_definition : attribute* access_modifier? STRUCT IDENTIFIER generic_definition? type_implements? (INDENT struct_entry+ DEDENT | NL) ; // Interface declaration. interface_definition : attribute* access_modifier? INTERFACE IDENTIFIER generic_definition? type_implements? (INDENT struct_entry+ DEDENT | NL) ; // Implementation declaration. implementation_definition : IMPL variable_or_function (FOR variable_type)? generic_definition? (INDENT implementation_entry+ DEDENT | NL) ; // Implementation entry. implementation_entry : function_definition #ImplementationEntryFunction | constructor_definition #ImplementationEntryConstructor | operator_definition #ImplementationEntryOperator | cast_definition #ImplementationEntryCast | NL #ImplementationBlank ; // Cast definition. cast_definition : attribute* INLINE? (IMPLICITCAST | EXPLICITCAST) '(' variable_parameter ')' OP_RET variable_type (INDENT code_statement+ DEDENT | OP_LAMBDA expression NL) ; // Typedef definition. typedef_definition : TYPEDEF variable_type IDENTIFIER NL ; // Struct entry. struct_entry : access_modifier? variable_parameter (struct_entry_property | NL) #StructData | access_modifier NL #StructAccess | NL #StructBlank ; // Struct entry properties. struct_entry_property : INDENT (access_modifier? GET (NL | code_body | OP_LAMBDA expression NL))? (access_modifier? SET (NL | code_body | OP_LAMBDA expression NL))? DEDENT #PropertyGetSet | OP_LAMBDA expression NL #PropertySetOnly ; // Code body. code_body : INDENT code_statement+ DEDENT ; // Code statement. code_statement // : (';' | NL) #BlankStatement Causes problems currently. : variable_declaration NL #VariableDeclarationStatement | loop #LoopStatement | while_loop #WhileLoopStatement | do_while_loop #DoWhileLoopStatement | for_loop #ForLoopStatement | break_statement #BreakStatement | continue_statement #ContinueStatement | if_statement #IfStatement | switch_case #SwitchCaseStatement | expression NL #ExpressionStatement | UNSAFE INDENT code_statement* DEDENT #IndentedStatement | return_value NL #ReturnStatement | NL #BlankStatement ; // Infinite loop. loop : LOOP code_body ; // While loop. while_loop : WHILE expression code_body ; // Do while loop. do_while_loop : DO code_body WHILE expression NL ; // For loop. for_loop : FOR '(' (variable_assignment | variable_declaration)? ';' expression ';' expression ')' code_body #TraditionalForLoop | FOR (variable_assignment | variable_declaration)? ';' expression ';' expression code_body #TraditionalForLoopNoParens | FOR '(' (variable_parameter | IDENTIFIER) IN expression ')' code_body #ForEachLoop | FOR (variable_parameter | IDENTIFIER) IN expression code_body #ForEachLoopNoParens ; //Break. break_statement : BREAK INTEGER? NL ; // Continue. continue_statement : CONTINUE NL ; // If statement. if_statement : CONST? IF expression code_body (ELIF expression code_body)* (ELSE code_body)? ; // Switch case. switch_case : SWITCH '(' variable_or_function (OP_LAMBDA IDENTIFIER)? ')' INDENT switch_rule+ DEDENT #SwitchCase | SWITCH variable_or_function (OP_LAMBDA IDENTIFIER)? INDENT switch_rule+ DEDENT #SwitchCaseNoParens ; // Switch rule. switch_rule : (CASE expression ':' NL*)+ INDENT code_statement+ BREAK DEDENT NL #CaseExpression | DEFAULT ':' INDENT code_statement+ BREAK DEDENT NL #CaseDefault ; // Function call. Can also be a constructor. function_call : AWAIT? variable_or_function generic_specifier? '(' (label? expression (',' label? expression)*)? ')' ; // Constructor with initializers. constructor_with_initializers : NEW? variable_type ('(' (expression (',' expression)*)? ')')? '{' (initializer_value (',' initializer_value)*)? '}' ; // Initializer value. initializer_value : (IDENTIFIER ('.' IDENTIFIER)* ':')? expression ; // Return value. return_value : RETURN expression ; // Type implements extended. type_implements_extended : ':' type_implements_extended_expression ; // Type implements extended expression. type_implements_extended_expression : '(' type_implements_extended_expression ')' #TypeImplementsExprParenthesis | type_implements_extended_expression '|' type_implements_extended_expression #TypeImplementsExprOr | type_implements_extended_expression ',' type_implements_extended_expression #TypeImplementsExprAnd | variable_type #TypeImplementsExprSingle ; // Type implements. type_implements : ':' variable_type (',' variable_type)* ; // Generic definition. generic_definition : '<' IDENTIFIER type_implements_extended? (',' IDENTIFIER type_implements_extended?)* '>' ; // Generic specifier. generic_specifier : '<' variable_type (',' variable_type)* '>' ; // Expression. expression : '(' expression ')' #ExprParenthesis | primary_expression #ExprPrimary | expression '(' expression ')' #ExprCallReturnedFunction | expression (OP_PLUS_PLUS | OP_MINUS_MINUS | OP_NOT) #ExprSubprimary | unary_expression #ExprUnary // Something is weird here with the order of operations. | expression OP_RANGE '='? expression #ExprRange | expression (OP_MUL | OP_DIV | OP_MOD) expression #ExprMultiplicative | expression (OP_ADD | OP_SUB) expression #ExprAdditive | expression (OP_LSHIFT | OP_RSHIFT) expression #ExprShift | expression (OP_LT | OP_GT | OP_LE | OP_GE | IS | AS) expression #ExprComparison | expression (OP_EQ | OP_NE) expression #ExprEqualityComparison | expression OP_ADDRESS_OF expression #ExprBitAnd | expression OP_MEMBER_ACCESS expression #ExprXor | expression OP_BITWISE_OR expression #ExprBitOr | expression OP_AND expression #ExprAnd | expression OP_OR expression #ExprOr | expression OP_NULL_CHECK expression #ExprNullCheck | expression '?' expression ':' expression #ExprTernary | expression OP_LAMBDA expression #ExprLambda | expression assignment_operator expression #ExprAssignment | expression ',' expression #ExprComma | UNSAFE? INDENT code_statement+ DEDENT #ExprCode | INTEGER #ExprInteger | STRING #ExprString ; // Primary expression. primary_expression : variable_or_function | constructor_with_initializers | function_call | NEW function_call | TYPEOF '(' (variable_or_function | variable_type) ')' | SIZEOF '(' (variable_or_function | variable_type) ')' ; // Unary expression. unary_expression : OP_ADD expression | OP_SUB expression | OP_NOT expression | OP_TILDE expression | OP_PLUS_PLUS expression | OP_MINUS_MINUS expression | OP_MEMBER_ACCESS expression | '(' variable_type ')' expression | OP_ADDRESS_OF expression | OP_REFERENCE_POINTER expression | OP_MUL expression | defined_constants ; // Access modifier. access_modifier : PUBLIC | PROTECTED INTERNAL | PRIVATE PROTECTED | PRIVATE | PROTECTED | INTERNAL ; // Variable assignment. variable_assignment : variable_or_function (',' variable_or_function)+ assignment_operator expression #VariableAssignmentUnpack | variable_or_function ('=' variable_or_function)* assignment_operator expression #VariableAssignmentNormal ; // Variable declaration. variable_declaration : attribute* variable_parameter ('=' variable_parameter)* ASSIGN_OP_EQ NEW? (constructor_with_initializers | function_call) #VariableDeclareWithInitializer | attribute* variable_parameter (',' variable_parameter)* ASSIGN_OP_EQ NEW? (constructor_with_initializers | function_call) #VariableDeclareWithTupleInitializer | attribute* variable_parameter ('=' variable_parameter)* ASSIGN_OP_EQ expression #VariableDeclareWithInitializerExpr | attribute* variable_parameter (',' variable_parameter)* ASSIGN_OP_EQ expression #VariableDeclareWithTupleInitializerExpr | attribute* variable_parameter (',' IDENTIFIER)* #VariableDeclareWithoutInitializer | attribute* variable_parameter (',' variable_parameter)* #VariableDeclareWithoutInitializerMultipleTypes ; // Label. label : IDENTIFIER ':' ; // Variable arguments. variable_arguments : (label? variable_parameter (',' label? variable_parameter)* (',' '...' IDENTIFIER (':' variable_type)?)?)? #VariableArgsNoneOrSome | '...' IDENTIFIER (':' variable_type)? #VariableArgsVariadicOnly ; // Variable parameter. variable_parameter : IDENTIFIER ':' variable_type ; // Variable type. variable_type : primitives #VarTypePrimitive | '(' variable_type (',' variable_type)+ ')' #VarTypeTupleProper | variable_type '*' #VarTypePointer | variable_type '&' #VarTypeReference | variable_type '[' INTEGER? (',' INTEGER?)* ']' #VarTypeArray | variable_type '<' variable_type (',' variable_type)* '>' #VarTypeGenerics | variable_type (',' variable_type)+ #VarTypeTuple | CONST variable_type #VarTypeConstant | STATIC variable_type #VarTypeStatic | VOLATILE variable_type #VarTypeVolatile | ATOMIC '<' variable_type '>' #VarTypeAtomic | variable_or_function #VarTypeCustom | 'This' #VarTypeThis ; // Primitive types. It turns out rules rely on spaces sometimes. Who knew. primitives : 'string' #PrimitiveString | 'bool' #PrimitiveBool | UNSIGNED #PrimitiveUnsigned | SIGNED #PrimitiveSigned | 'f16' #PrimitiveHalf | 'f32' #PrimitiveFloat | 'f64' #PrimitiveDouble | 'f80' #PrimitiveExtended | 'f128' #PrimitiveDecimal | FIXED #PrimitiveFixed | 'varlen' #PrimitiveVarLen | 'object' #PrimitiveObject | 'void' #PrimitiveVoid | 'func' ('<' variable_type (',' variable_type)* '>')? #PrimitiveFunction | 'event' ('<' variable_type (',' variable_type)* '>')? #PrimitiveEvent | 'char' #PrimitiveChar | 'wchar' #PrimitiveWideChar | 'var' #PrimitiveAutoVariable | 'unsigned' #PrimitiveUnsignedAny | 'signed' #PrimitiveSignedAny | 'floating' #PrimitiveFloatingAny | 'fixed' #PrimitiveFixedAny ; // Defined constants. defined_constants : 'true' #ConstantTrue | 'false' #ConstantFalse | 'null' #ConstantNull ; // Variable or function. variable_or_function : IDENTIFIER ('.' IDENTIFIER)* | primitives ; // Operator. operator : assignment_operator | OP_ADD | OP_AND | OP_ADDRESS_OF | OP_BITWISE_OR | OP_DIV | OP_EQ | OP_GE | OP_GT | OP_LE | OP_LT | OP_LSHIFT | OP_MEMBER_ACCESS | OP_MINUS_MINUS | OP_MOD | OP_MUL | OP_OR | OP_NAND | OP_NE | OP_NOR | OP_NOT | OP_PLUS_PLUS | OP_RANGE | OP_RSHIFT | OP_SUB | OP_TILDE ; // Assignment operator. assignment_operator : ASSIGN_OP_EQ | ASSIGN_OP_ADD_EQ | ASSIGN_OP_SUB_EQ | ASSIGN_OP_EXP_EQ | ASSIGN_OP_MUL_EQ | ASSIGN_OP_DIV_EQ | ASSIGN_OP_MOD_EQ | ASSIGN_OP_BITAND_EQ | ASSIGN_OP_BITOR_EQ | ASSIGN_OP_XOR_EQ | ASSIGN_OP_BITFLIP_EQ | ASSIGN_OP_LSHIFT_EQ | ASSIGN_OP_RSHIFT_EQ | ASSIGN_OP_AND_EQ | ASSIGN_OP_OR_EQ | ASSIGN_OP_NAND_EQ | ASSIGN_OP_NOR_EQ | ASSIGN_OP_CHECK_NULL ; // Keywords. AS: 'as'; ASYNC: 'async'; ATOMIC: 'atomic'; AWAIT: 'await'; BREAK: 'break'; CASE: 'case'; CONST: 'const'; CONTINUE: 'continue'; DEFAULT: 'default'; DO: 'do'; ELIF: 'else if'; ELSE: 'else'; ENUM: 'enum'; EXPLICITCAST: 'explicitcast'; EXTERN: 'extern'; FOR: 'for'; FUNCTION: 'fn'; GET: 'get'; IF: 'if'; IMPL: 'impl'; IMPLICITCAST: 'implicitcast'; IN: 'in'; INLINE: 'inline'; INTERFACE: 'interface'; INTERNAL: 'internal'; IS: 'is'; LOOP: 'loop'; NAMESPACE: 'namespace'; NEW: 'new'; OPERATOR: 'operator'; PRIVATE: 'private' | 'pri'; PROTECTED: 'protected' | 'pro'; PUBLIC: 'public' | 'pub'; RETURN: 'return'; SET: 'set'; SIZEOF: 'sizeof'; STATIC: 'static'; STRUCT: 'struct'; SWITCH: 'switch'; TYPEDEF: 'typedef'; TYPEOF: 'typeof'; UNSAFE: 'unsafe'; UNION: 'union'; USING: 'using'; VOLATILE: 'volatile'; WHILE: 'while'; // Assignment operators. ASSIGN_OP_EQ: '='; ASSIGN_OP_ADD_EQ: '+='; ASSIGN_OP_SUB_EQ: '-='; ASSIGN_OP_EXP_EQ: '**='; ASSIGN_OP_MUL_EQ: '*='; ASSIGN_OP_DIV_EQ: '/='; ASSIGN_OP_MOD_EQ: '%='; ASSIGN_OP_BITAND_EQ: '&='; ASSIGN_OP_BITOR_EQ: '|='; ASSIGN_OP_XOR_EQ: '^='; ASSIGN_OP_BITFLIP_EQ: '~='; ASSIGN_OP_LSHIFT_EQ: '<<='; ASSIGN_OP_RSHIFT_EQ: '>>='; ASSIGN_OP_AND_EQ: '&&='; ASSIGN_OP_OR_EQ: '||='; ASSIGN_OP_NAND_EQ: '!&='; ASSIGN_OP_NOR_EQ: '!|='; ASSIGN_OP_CHECK_NULL: '??='; // Operators. OP_ADD: '+'; OP_ADDRESS_OF: '&'; OP_AND: '&&'; OP_BITWISE_OR: '|'; OP_DIV: '/'; OP_EQ: '=='; OP_GE: '>='; OP_GT: '>'; OP_LAMBDA: '=>'; OP_LE: '<='; OP_LSHIFT: '<<'; OP_LT: '<'; OP_MEMBER_ACCESS: '^'; OP_MINUS_MINUS: '--'; OP_MOD: '%'; OP_MUL: '*'; OP_NAND: '!&'; OP_NE: '!='; OP_NOR: '!|'; OP_NOT: '!'; OP_NULL_CHECK: '??'; OP_OR: '||'; OP_PLUS_PLUS: '++'; OP_RANGE: '..'; OP_REFERENCE_POINTER: '@'; OP_RET: '->'; OP_RSHIFT: '>>'; OP_SUB: '-'; OP_TILDE: '~'; // Unsigned. UNSIGNED : 'u' DecDigit+ ; // Signed. SIGNED : 's' DecDigit+ ; // Fixed. FIXED : 'fix' DecDigit+ 'x' DecDigit+ ; // Whole nubmer. INTEGER : '-'? DecDigit+ | '-'? '0x' HexDigit+ | '-'? '0b' BinDigit+ | '-'? DecDigit IntegerTypeSuffix ; // Basic blocks. IDENTIFIER: '@'? IdentifierOrKeyword; ESCAPE_SEQUENCE: SimpleEscapeSequence | HexEscapeSequence; STRING: '""' ((SimpleEscapeSequence | HexEscapeSequence)|.)*? '""'; LINE_COMMENT : '//' .*? '\\r'? '\\n' -> skip; COMMENT : '/*' .*? '*/' -> skip; NL: ('\\r'? '\\n' ' '*); WHITESPACE: Whitespace -> skip; // Fragments fragment InputCharacter: ~[\\r\\n\\u0085\\u2028\\u2029]; fragment NewLineCharacter : '\\u000D' //'' | '\\u000A' //'' | '\\u0085' //'' | '\\u2028' //'' | '\\u2029' //'' ; fragment IntegerTypeSuffix: [uU] | [sS]; fragment HexDigit: [0-9] | [A-F] | [a-f]; fragment BinDigit: [0-1]; fragment DecDigit: [0-9]; fragment ExponentPart: [eE] ('+' | '-')? [0-9] ('_'* [0-9])*; fragment CommonCharacter : SimpleEscapeSequence | HexEscapeSequence | UnicodeEscapeSequence ; fragment SimpleEscapeSequence : '\\\\\\'' | '\\\\""' | '\\\\\\\\' | '\\\\0' | '\\\\a' | '\\\\b' | '\\\\f' | '\\\\n' | '\\\\r' | '\\\\t' | '\\\\v' ; fragment HexEscapeSequence : '\\\\x' HexDigit | '\\\\x' HexDigit HexDigit | '\\\\x' HexDigit HexDigit HexDigit | '\\\\x' HexDigit HexDigit HexDigit HexDigit ; fragment NewLine : '\\r\\n' | '\\r' | '\\n' | '\\u0085' // ' | '\\u2028' //'' | '\\u2029' //'' ; fragment Whitespace : UnicodeClassZS //'' | '\\u0009' //'' | '\\u000B' //'' | '\\u000C' //'
' ; fragment UnicodeClassZS : '\\u0020' // SPACE | '\\u00A0' // NO_BREAK SPACE | '\\u1680' // OGHAM SPACE MARK | '\\u180E' // MONGOLIAN VOWEL SEPARATOR | '\\u2000' // EN QUAD | '\\u2001' // EM QUAD | '\\u2002' // EN SPACE | '\\u2003' // EM SPACE | '\\u2004' // THREE_PER_EM SPACE | '\\u2005' // FOUR_PER_EM SPACE | '\\u2006' // SIX_PER_EM SPACE | '\\u2008' // PUNCTUATION SPACE | '\\u2009' // THIN SPACE | '\\u200A' // HAIR SPACE | '\\u202F' // NARROW NO_BREAK SPACE | '\\u3000' // IDEOGRAPHIC SPACE | '\\u205F' // MEDIUM MATHEMATICAL SPACE ; fragment IdentifierOrKeyword : IdentifierStartCharacter IdentifierPartCharacter* ; fragment IdentifierStartCharacter : LetterCharacter | '_' ; fragment IdentifierPartCharacter : LetterCharacter | DecimalDigitCharacter | ConnectingCharacter | CombiningCharacter | FormattingCharacter ; //'' // WARNING: ignores UnicodeEscapeSequence fragment LetterCharacter : UnicodeClassLU | UnicodeClassLL | UnicodeClassLT | UnicodeClassLM | UnicodeClassLO | UnicodeClassNL | UnicodeEscapeSequence ; //'' // WARNING: ignores UnicodeEscapeSequence fragment DecimalDigitCharacter : UnicodeClassND | UnicodeEscapeSequence ; //'' // WARNING: ignores UnicodeEscapeSequence fragment ConnectingCharacter : UnicodeClassPC | UnicodeEscapeSequence ; //'' // WARNING: ignores UnicodeEscapeSequence fragment CombiningCharacter : UnicodeClassMN | UnicodeClassMC | UnicodeEscapeSequence ; //'' // WARNING: ignores UnicodeEscapeSequence fragment FormattingCharacter : UnicodeClassCF | UnicodeEscapeSequence ; //B.1.5 Unicode Character Escape Sequences fragment UnicodeEscapeSequence : '\\\\u' HexDigit HexDigit HexDigit HexDigit | '\\\\U' HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit ; // Unicode character classes fragment UnicodeClassLU : '\\u0041'..'\\u005a' | '\\u00c0'..'\\u00d6' | '\\u00d8'..'\\u00de' | '\\u0100'..'\\u0136' | '\\u0139'..'\\u0147' | '\\u014a'..'\\u0178' | '\\u0179'..'\\u017d' | '\\u0181'..'\\u0182' | '\\u0184'..'\\u0186' | '\\u0187'..'\\u0189' | '\\u018a'..'\\u018b' | '\\u018e'..'\\u0191' | '\\u0193'..'\\u0194' | '\\u0196'..'\\u0198' | '\\u019c'..'\\u019d' | '\\u019f'..'\\u01a0' | '\\u01a2'..'\\u01a6' | '\\u01a7'..'\\u01a9' | '\\u01ac'..'\\u01ae' | '\\u01af'..'\\u01b1' | '\\u01b2'..'\\u01b3' | '\\u01b5'..'\\u01b7' | '\\u01b8'..'\\u01bc' | '\\u01c4'..'\\u01cd' | '\\u01cf'..'\\u01db' | '\\u01de'..'\\u01ee' | '\\u01f1'..'\\u01f4' | '\\u01f6'..'\\u01f8' | '\\u01fa'..'\\u0232' | '\\u023a'..'\\u023b' | '\\u023d'..'\\u023e' | '\\u0241'..'\\u0243' | '\\u0244'..'\\u0246' | '\\u0248'..'\\u024e' | '\\u0370'..'\\u0372' | '\\u0376'..'\\u037f' | '\\u0386'..'\\u0388' | '\\u0389'..'\\u038a' | '\\u038c'..'\\u038e' | '\\u038f'..'\\u0391' | '\\u0392'..'\\u03a1' | '\\u03a3'..'\\u03ab' | '\\u03cf'..'\\u03d2' | '\\u03d3'..'\\u03d4' | '\\u03d8'..'\\u03ee' | '\\u03f4'..'\\u03f7' | '\\u03f9'..'\\u03fa' | '\\u03fd'..'\\u042f' | '\\u0460'..'\\u0480' | '\\u048a'..'\\u04c0' | '\\u04c1'..'\\u04cd' | '\\u04d0'..'\\u052e' | '\\u0531'..'\\u0556' | '\\u10a0'..'\\u10c5' | '\\u10c7'..'\\u10cd' | '\\u1e00'..'\\u1e94' | '\\u1e9e'..'\\u1efe' | '\\u1f08'..'\\u1f0f' | '\\u1f18'..'\\u1f1d' | '\\u1f28'..'\\u1f2f' | '\\u1f38'..'\\u1f3f' | '\\u1f48'..'\\u1f4d' | '\\u1f59'..'\\u1f5f' | '\\u1f68'..'\\u1f6f' | '\\u1fb8'..'\\u1fbb' | '\\u1fc8'..'\\u1fcb' | '\\u1fd8'..'\\u1fdb' | '\\u1fe8'..'\\u1fec' | '\\u1ff8'..'\\u1ffb' | '\\u2102'..'\\u2107' | '\\u210b'..'\\u210d' | '\\u2110'..'\\u2112' | '\\u2115'..'\\u2119' | '\\u211a'..'\\u211d' | '\\u2124'..'\\u212a' | '\\u212b'..'\\u212d' | '\\u2130'..'\\u2133' | '\\u213e'..'\\u213f' | '\\u2145'..'\\u2183' | '\\u2c00'..'\\u2c2e' | '\\u2c60'..'\\u2c62' | '\\u2c63'..'\\u2c64' | '\\u2c67'..'\\u2c6d' | '\\u2c6e'..'\\u2c70' | '\\u2c72'..'\\u2c75' | '\\u2c7e'..'\\u2c80' | '\\u2c82'..'\\u2ce2' | '\\u2ceb'..'\\u2ced' | '\\u2cf2'..'\\ua640' | '\\ua642'..'\\ua66c' | '\\ua680'..'\\ua69a' | '\\ua722'..'\\ua72e' | '\\ua732'..'\\ua76e' | '\\ua779'..'\\ua77d' | '\\ua77e'..'\\ua786' | '\\ua78b'..'\\ua78d' | '\\ua790'..'\\ua792' | '\\ua796'..'\\ua7aa' | '\\ua7ab'..'\\ua7ad' | '\\ua7b0'..'\\ua7b1' | '\\uff21'..'\\uff3a' ; fragment UnicodeClassLL : '\\u0061'..'\\u007A' | '\\u00b5'..'\\u00df' | '\\u00e0'..'\\u00f6' | '\\u00f8'..'\\u00ff' | '\\u0101'..'\\u0137' | '\\u0138'..'\\u0148' | '\\u0149'..'\\u0177' | '\\u017a'..'\\u017e' | '\\u017f'..'\\u0180' | '\\u0183'..'\\u0185' | '\\u0188'..'\\u018c' | '\\u018d'..'\\u0192' | '\\u0195'..'\\u0199' | '\\u019a'..'\\u019b' | '\\u019e'..'\\u01a1' | '\\u01a3'..'\\u01a5' | '\\u01a8'..'\\u01aa' | '\\u01ab'..'\\u01ad' | '\\u01b0'..'\\u01b4' | '\\u01b6'..'\\u01b9' | '\\u01ba'..'\\u01bd' | '\\u01be'..'\\u01bf' | '\\u01c6'..'\\u01cc' | '\\u01ce'..'\\u01dc' | '\\u01dd'..'\\u01ef' | '\\u01f0'..'\\u01f3' | '\\u01f5'..'\\u01f9' | '\\u01fb'..'\\u0233' | '\\u0234'..'\\u0239' | '\\u023c'..'\\u023f' | '\\u0240'..'\\u0242' | '\\u0247'..'\\u024f' | '\\u0250'..'\\u0293' | '\\u0295'..'\\u02af' | '\\u0371'..'\\u0373' | '\\u0377'..'\\u037b' | '\\u037c'..'\\u037d' | '\\u0390'..'\\u03ac' | '\\u03ad'..'\\u03ce' | '\\u03d0'..'\\u03d1' | '\\u03d5'..'\\u03d7' | '\\u03d9'..'\\u03ef' | '\\u03f0'..'\\u03f3' | '\\u03f5'..'\\u03fb' | '\\u03fc'..'\\u0430' | '\\u0431'..'\\u045f' | '\\u0461'..'\\u0481' | '\\u048b'..'\\u04bf' | '\\u04c2'..'\\u04ce' | '\\u04cf'..'\\u052f' | '\\u0561'..'\\u0587' | '\\u1d00'..'\\u1d2b' | '\\u1d6b'..'\\u1d77' | '\\u1d79'..'\\u1d9a' | '\\u1e01'..'\\u1e95' | '\\u1e96'..'\\u1e9d' | '\\u1e9f'..'\\u1eff' | '\\u1f00'..'\\u1f07' | '\\u1f10'..'\\u1f15' | '\\u1f20'..'\\u1f27' | '\\u1f30'..'\\u1f37' | '\\u1f40'..'\\u1f45' | '\\u1f50'..'\\u1f57' | '\\u1f60'..'\\u1f67' | '\\u1f70'..'\\u1f7d' | '\\u1f80'..'\\u1f87' | '\\u1f90'..'\\u1f97' | '\\u1fa0'..'\\u1fa7' | '\\u1fb0'..'\\u1fb4' | '\\u1fb6'..'\\u1fb7' | '\\u1fbe'..'\\u1fc2' | '\\u1fc3'..'\\u1fc4' | '\\u1fc6'..'\\u1fc7' | '\\u1fd0'..'\\u1fd3' | '\\u1fd6'..'\\u1fd7' | '\\u1fe0'..'\\u1fe7' | '\\u1ff2'..'\\u1ff4' | '\\u1ff6'..'\\u1ff7' | '\\u210a'..'\\u210e' | '\\u210f'..'\\u2113' | '\\u212f'..'\\u2139' | '\\u213c'..'\\u213d' | '\\u2146'..'\\u2149' | '\\u214e'..'\\u2184' | '\\u2c30'..'\\u2c5e' | '\\u2c61'..'\\u2c65' | '\\u2c66'..'\\u2c6c' | '\\u2c71'..'\\u2c73' | '\\u2c74'..'\\u2c76' | '\\u2c77'..'\\u2c7b' | '\\u2c81'..'\\u2ce3' | '\\u2ce4'..'\\u2cec' | '\\u2cee'..'\\u2cf3' | '\\u2d00'..'\\u2d25' | '\\u2d27'..'\\u2d2d' | '\\ua641'..'\\ua66d' | '\\ua681'..'\\ua69b' | '\\ua723'..'\\ua72f' | '\\ua730'..'\\ua731' | '\\ua733'..'\\ua771' | '\\ua772'..'\\ua778' | '\\ua77a'..'\\ua77c' | '\\ua77f'..'\\ua787' | '\\ua78c'..'\\ua78e' | '\\ua791'..'\\ua793' | '\\ua794'..'\\ua795' | '\\ua797'..'\\ua7a9' | '\\ua7fa'..'\\uab30' | '\\uab31'..'\\uab5a' | '\\uab64'..'\\uab65' | '\\ufb00'..'\\ufb06' | '\\ufb13'..'\\ufb17' | '\\uff41'..'\\uff5a' ; fragment UnicodeClassLT : '\\u01c5'..'\\u01cb' | '\\u01f2'..'\\u1f88' | '\\u1f89'..'\\u1f8f' | '\\u1f98'..'\\u1f9f' | '\\u1fa8'..'\\u1faf' | '\\u1fbc'..'\\u1fcc' | '\\u1ffc'..'\\u1ffc' ; fragment UnicodeClassLM : '\\u02b0'..'\\u02c1' | '\\u02c6'..'\\u02d1' | '\\u02e0'..'\\u02e4' | '\\u02ec'..'\\u02ee' | '\\u0374'..'\\u037a' | '\\u0559'..'\\u0640' | '\\u06e5'..'\\u06e6' | '\\u07f4'..'\\u07f5' | '\\u07fa'..'\\u081a' | '\\u0824'..'\\u0828' | '\\u0971'..'\\u0e46' | '\\u0ec6'..'\\u10fc' | '\\u17d7'..'\\u1843' | '\\u1aa7'..'\\u1c78' | '\\u1c79'..'\\u1c7d' | '\\u1d2c'..'\\u1d6a' | '\\u1d78'..'\\u1d9b' | '\\u1d9c'..'\\u1dbf' | '\\u2071'..'\\u207f' | '\\u2090'..'\\u209c' | '\\u2c7c'..'\\u2c7d' | '\\u2d6f'..'\\u2e2f' | '\\u3005'..'\\u3031' | '\\u3032'..'\\u3035' | '\\u303b'..'\\u309d' | '\\u309e'..'\\u30fc' | '\\u30fd'..'\\u30fe' | '\\ua015'..'\\ua4f8' | '\\ua4f9'..'\\ua4fd' | '\\ua60c'..'\\ua67f' | '\\ua69c'..'\\ua69d' | '\\ua717'..'\\ua71f' | '\\ua770'..'\\ua788' | '\\ua7f8'..'\\ua7f9' | '\\ua9cf'..'\\ua9e6' | '\\uaa70'..'\\uaadd' | '\\uaaf3'..'\\uaaf4' | '\\uab5c'..'\\uab5f' | '\\uff70'..'\\uff9e' | '\\uff9f'..'\\uff9f' ; fragment UnicodeClassLO : '\\u00aa'..'\\u00ba' | '\\u01bb'..'\\u01c0' | '\\u01c1'..'\\u01c3' | '\\u0294'..'\\u05d0' | '\\u05d1'..'\\u05ea' | '\\u05f0'..'\\u05f2' | '\\u0620'..'\\u063f' | '\\u0641'..'\\u064a' | '\\u066e'..'\\u066f' | '\\u0671'..'\\u06d3' | '\\u06d5'..'\\u06ee' | '\\u06ef'..'\\u06fa' | '\\u06fb'..'\\u06fc' | '\\u06ff'..'\\u0710' | '\\u0712'..'\\u072f' | '\\u074d'..'\\u07a5' | '\\u07b1'..'\\u07ca' | '\\u07cb'..'\\u07ea' | '\\u0800'..'\\u0815' | '\\u0840'..'\\u0858' | '\\u08a0'..'\\u08b2' | '\\u0904'..'\\u0939' | '\\u093d'..'\\u0950' | '\\u0958'..'\\u0961' | '\\u0972'..'\\u0980' | '\\u0985'..'\\u098c' | '\\u098f'..'\\u0990' | '\\u0993'..'\\u09a8' | '\\u09aa'..'\\u09b0' | '\\u09b2'..'\\u09b6' | '\\u09b7'..'\\u09b9' | '\\u09bd'..'\\u09ce' | '\\u09dc'..'\\u09dd' | '\\u09df'..'\\u09e1' | '\\u09f0'..'\\u09f1' | '\\u0a05'..'\\u0a0a' | '\\u0a0f'..'\\u0a10' | '\\u0a13'..'\\u0a28' | '\\u0a2a'..'\\u0a30' | '\\u0a32'..'\\u0a33' | '\\u0a35'..'\\u0a36' | '\\u0a38'..'\\u0a39' | '\\u0a59'..'\\u0a5c' | '\\u0a5e'..'\\u0a72' | '\\u0a73'..'\\u0a74' | '\\u0a85'..'\\u0a8d' | '\\u0a8f'..'\\u0a91' | '\\u0a93'..'\\u0aa8' | '\\u0aaa'..'\\u0ab0' | '\\u0ab2'..'\\u0ab3' | '\\u0ab5'..'\\u0ab9' | '\\u0abd'..'\\u0ad0' | '\\u0ae0'..'\\u0ae1' | '\\u0b05'..'\\u0b0c' | '\\u0b0f'..'\\u0b10' | '\\u0b13'..'\\u0b28' | '\\u0b2a'..'\\u0b30' | '\\u0b32'..'\\u0b33' | '\\u0b35'..'\\u0b39' | '\\u0b3d'..'\\u0b5c' | '\\u0b5d'..'\\u0b5f' | '\\u0b60'..'\\u0b61' | '\\u0b71'..'\\u0b83' | '\\u0b85'..'\\u0b8a' | '\\u0b8e'..'\\u0b90' | '\\u0b92'..'\\u0b95' | '\\u0b99'..'\\u0b9a' | '\\u0b9c'..'\\u0b9e' | '\\u0b9f'..'\\u0ba3' | '\\u0ba4'..'\\u0ba8' | '\\u0ba9'..'\\u0baa' | '\\u0bae'..'\\u0bb9' | '\\u0bd0'..'\\u0c05' | '\\u0c06'..'\\u0c0c' | '\\u0c0e'..'\\u0c10' | '\\u0c12'..'\\u0c28' | '\\u0c2a'..'\\u0c39' | '\\u0c3d'..'\\u0c58' | '\\u0c59'..'\\u0c60' | '\\u0c61'..'\\u0c85' | '\\u0c86'..'\\u0c8c' | '\\u0c8e'..'\\u0c90' | '\\u0c92'..'\\u0ca8' | '\\u0caa'..'\\u0cb3' | '\\u0cb5'..'\\u0cb9' | '\\u0cbd'..'\\u0cde' | '\\u0ce0'..'\\u0ce1' | '\\u0cf1'..'\\u0cf2' | '\\u0d05'..'\\u0d0c' | '\\u0d0e'..'\\u0d10' | '\\u0d12'..'\\u0d3a' | '\\u0d3d'..'\\u0d4e' | '\\u0d60'..'\\u0d61' | '\\u0d7a'..'\\u0d7f' | '\\u0d85'..'\\u0d96' | '\\u0d9a'..'\\u0db1' | '\\u0db3'..'\\u0dbb' | '\\u0dbd'..'\\u0dc0' | '\\u0dc1'..'\\u0dc6' | '\\u0e01'..'\\u0e30' | '\\u0e32'..'\\u0e33' | '\\u0e40'..'\\u0e45' | '\\u0e81'..'\\u0e82' | '\\u0e84'..'\\u0e87' | '\\u0e88'..'\\u0e8a' | '\\u0e8d'..'\\u0e94' | '\\u0e95'..'\\u0e97' | '\\u0e99'..'\\u0e9f' | '\\u0ea1'..'\\u0ea3' | '\\u0ea5'..'\\u0ea7' | '\\u0eaa'..'\\u0eab' | '\\u0ead'..'\\u0eb0' | '\\u0eb2'..'\\u0eb3' | '\\u0ebd'..'\\u0ec0' | '\\u0ec1'..'\\u0ec4' | '\\u0edc'..'\\u0edf' | '\\u0f00'..'\\u0f40' | '\\u0f41'..'\\u0f47' | '\\u0f49'..'\\u0f6c' | '\\u0f88'..'\\u0f8c' | '\\u1000'..'\\u102a' | '\\u103f'..'\\u1050' | '\\u1051'..'\\u1055' | '\\u105a'..'\\u105d' | '\\u1061'..'\\u1065' | '\\u1066'..'\\u106e' | '\\u106f'..'\\u1070' | '\\u1075'..'\\u1081' | '\\u108e'..'\\u10d0' | '\\u10d1'..'\\u10fa' | '\\u10fd'..'\\u1248' | '\\u124a'..'\\u124d' | '\\u1250'..'\\u1256' | '\\u1258'..'\\u125a' | '\\u125b'..'\\u125d' | '\\u1260'..'\\u1288' | '\\u128a'..'\\u128d' | '\\u1290'..'\\u12b0' | '\\u12b2'..'\\u12b5' | '\\u12b8'..'\\u12be' | '\\u12c0'..'\\u12c2' | '\\u12c3'..'\\u12c5' | '\\u12c8'..'\\u12d6' | '\\u12d8'..'\\u1310' | '\\u1312'..'\\u1315' | '\\u1318'..'\\u135a' | '\\u1380'..'\\u138f' | '\\u13a0'..'\\u13f4' | '\\u1401'..'\\u166c' | '\\u166f'..'\\u167f' | '\\u1681'..'\\u169a' | '\\u16a0'..'\\u16ea' | '\\u16f1'..'\\u16f8' | '\\u1700'..'\\u170c' | '\\u170e'..'\\u1711' | '\\u1720'..'\\u1731' | '\\u1740'..'\\u1751' | '\\u1760'..'\\u176c' | '\\u176e'..'\\u1770' | '\\u1780'..'\\u17b3' | '\\u17dc'..'\\u1820' | '\\u1821'..'\\u1842' | '\\u1844'..'\\u1877' | '\\u1880'..'\\u18a8' | '\\u18aa'..'\\u18b0' | '\\u18b1'..'\\u18f5' | '\\u1900'..'\\u191e' | '\\u1950'..'\\u196d' | '\\u1970'..'\\u1974' | '\\u1980'..'\\u19ab' | '\\u19c1'..'\\u19c7' | '\\u1a00'..'\\u1a16' | '\\u1a20'..'\\u1a54' | '\\u1b05'..'\\u1b33' | '\\u1b45'..'\\u1b4b' | '\\u1b83'..'\\u1ba0' | '\\u1bae'..'\\u1baf' | '\\u1bba'..'\\u1be5' | '\\u1c00'..'\\u1c23' | '\\u1c4d'..'\\u1c4f' | '\\u1c5a'..'\\u1c77' | '\\u1ce9'..'\\u1cec' | '\\u1cee'..'\\u1cf1' | '\\u1cf5'..'\\u1cf6' | '\\u2135'..'\\u2138' | '\\u2d30'..'\\u2d67' | '\\u2d80'..'\\u2d96' | '\\u2da0'..'\\u2da6' | '\\u2da8'..'\\u2dae' | '\\u2db0'..'\\u2db6' | '\\u2db8'..'\\u2dbe' | '\\u2dc0'..'\\u2dc6' | '\\u2dc8'..'\\u2dce' | '\\u2dd0'..'\\u2dd6' | '\\u2dd8'..'\\u2dde' | '\\u3006'..'\\u303c' | '\\u3041'..'\\u3096' | '\\u309f'..'\\u30a1' | '\\u30a2'..'\\u30fa' | '\\u30ff'..'\\u3105' | '\\u3106'..'\\u312d' | '\\u3131'..'\\u318e' | '\\u31a0'..'\\u31ba' | '\\u31f0'..'\\u31ff' | '\\u3400'..'\\u4db5' | '\\u4e00'..'\\u9fcc' | '\\ua000'..'\\ua014' | '\\ua016'..'\\ua48c' | '\\ua4d0'..'\\ua4f7' | '\\ua500'..'\\ua60b' | '\\ua610'..'\\ua61f' | '\\ua62a'..'\\ua62b' | '\\ua66e'..'\\ua6a0' | '\\ua6a1'..'\\ua6e5' | '\\ua7f7'..'\\ua7fb' | '\\ua7fc'..'\\ua801' | '\\ua803'..'\\ua805' | '\\ua807'..'\\ua80a' | '\\ua80c'..'\\ua822' | '\\ua840'..'\\ua873' | '\\ua882'..'\\ua8b3' | '\\ua8f2'..'\\ua8f7' | '\\ua8fb'..'\\ua90a' | '\\ua90b'..'\\ua925' | '\\ua930'..'\\ua946' | '\\ua960'..'\\ua97c' | '\\ua984'..'\\ua9b2' | '\\ua9e0'..'\\ua9e4' | '\\ua9e7'..'\\ua9ef' | '\\ua9fa'..'\\ua9fe' | '\\uaa00'..'\\uaa28' | '\\uaa40'..'\\uaa42' | '\\uaa44'..'\\uaa4b' | '\\uaa60'..'\\uaa6f' | '\\uaa71'..'\\uaa76' | '\\uaa7a'..'\\uaa7e' | '\\uaa7f'..'\\uaaaf' | '\\uaab1'..'\\uaab5' | '\\uaab6'..'\\uaab9' | '\\uaaba'..'\\uaabd' | '\\uaac0'..'\\uaac2' | '\\uaadb'..'\\uaadc' | '\\uaae0'..'\\uaaea' | '\\uaaf2'..'\\uab01' | '\\uab02'..'\\uab06' | '\\uab09'..'\\uab0e' | '\\uab11'..'\\uab16' | '\\uab20'..'\\uab26' | '\\uab28'..'\\uab2e' | '\\uabc0'..'\\uabe2' | '\\uac00'..'\\ud7a3' | '\\ud7b0'..'\\ud7c6' | '\\ud7cb'..'\\ud7fb' | '\\uf900'..'\\ufa6d' | '\\ufa70'..'\\ufad9' | '\\ufb1d'..'\\ufb1f' | '\\ufb20'..'\\ufb28' | '\\ufb2a'..'\\ufb36' | '\\ufb38'..'\\ufb3c' | '\\ufb3e'..'\\ufb40' | '\\ufb41'..'\\ufb43' | '\\ufb44'..'\\ufb46' | '\\ufb47'..'\\ufbb1' | '\\ufbd3'..'\\ufd3d' | '\\ufd50'..'\\ufd8f' | '\\ufd92'..'\\ufdc7' | '\\ufdf0'..'\\ufdfb' | '\\ufe70'..'\\ufe74' | '\\ufe76'..'\\ufefc' | '\\uff66'..'\\uff6f' | '\\uff71'..'\\uff9d' | '\\uffa0'..'\\uffbe' | '\\uffc2'..'\\uffc7' | '\\uffca'..'\\uffcf' | '\\uffd2'..'\\uffd7' | '\\uffda'..'\\uffdc' ; fragment UnicodeClassNL : '\\u16EE' // RUNIC ARLAUG SYMBOL | '\\u16EF' // RUNIC TVIMADUR SYMBOL | '\\u16F0' // RUNIC BELGTHOR SYMBOL | '\\u2160' // ROMAN NUMERAL ONE | '\\u2161' // ROMAN NUMERAL TWO | '\\u2162' // ROMAN NUMERAL THREE | '\\u2163' // ROMAN NUMERAL FOUR | '\\u2164' // ROMAN NUMERAL FIVE | '\\u2165' // ROMAN NUMERAL SIX | '\\u2166' // ROMAN NUMERAL SEVEN | '\\u2167' // ROMAN NUMERAL EIGHT | '\\u2168' // ROMAN NUMERAL NINE | '\\u2169' // ROMAN NUMERAL TEN | '\\u216A' // ROMAN NUMERAL ELEVEN | '\\u216B' // ROMAN NUMERAL TWELVE | '\\u216C' // ROMAN NUMERAL FIFTY | '\\u216D' // ROMAN NUMERAL ONE HUNDRED | '\\u216E' // ROMAN NUMERAL FIVE HUNDRED | '\\u216F' // ROMAN NUMERAL ONE THOUSAND ; fragment UnicodeClassMN : '\\u0300' // COMBINING GRAVE ACCENT | '\\u0301' // COMBINING ACUTE ACCENT | '\\u0302' // COMBINING CIRCUMFLEX ACCENT | '\\u0303' // COMBINING TILDE | '\\u0304' // COMBINING MACRON | '\\u0305' // COMBINING OVERLINE | '\\u0306' // COMBINING BREVE | '\\u0307' // COMBINING DOT ABOVE | '\\u0308' // COMBINING DIAERESIS | '\\u0309' // COMBINING HOOK ABOVE | '\\u030A' // COMBINING RING ABOVE | '\\u030B' // COMBINING DOUBLE ACUTE ACCENT | '\\u030C' // COMBINING CARON | '\\u030D' // COMBINING VERTICAL LINE ABOVE | '\\u030E' // COMBINING DOUBLE VERTICAL LINE ABOVE | '\\u030F' // COMBINING DOUBLE GRAVE ACCENT | '\\u0310' // COMBINING CANDRABINDU ; fragment UnicodeClassMC : '\\u0903' // DEVANAGARI SIGN VISARGA | '\\u093E' // DEVANAGARI VOWEL SIGN AA | '\\u093F' // DEVANAGARI VOWEL SIGN I | '\\u0940' // DEVANAGARI VOWEL SIGN II | '\\u0949' // DEVANAGARI VOWEL SIGN CANDRA O | '\\u094A' // DEVANAGARI VOWEL SIGN SHORT O | '\\u094B' // DEVANAGARI VOWEL SIGN O | '\\u094C' // DEVANAGARI VOWEL SIGN AU ; fragment UnicodeClassCF : '\\u00AD' // SOFT HYPHEN | '\\u0600' // ARABIC NUMBER SIGN | '\\u0601' // ARABIC SIGN SANAH | '\\u0602' // ARABIC FOOTNOTE MARKER | '\\u0603' // ARABIC SIGN SAFHA | '\\u06DD' // ARABIC END OF AYAH ; fragment UnicodeClassPC : '\\u005F' // LOW LINE | '\\u203F' // UNDERTIE | '\\u2040' // CHARACTER TIE | '\\u2054' // INVERTED UNDERTIE | '\\uFE33' // PRESENTATION FORM FOR VERTICAL LOW LINE | '\\uFE34' // PRESENTATION FORM FOR VERTICAL WAVY LOW LINE | '\\uFE4D' // DASHED LOW LINE | '\\uFE4E' // CENTRELINE LOW LINE | '\\uFE4F' // WAVY LOW LINE | '\\uFF3F' // FULLWIDTH LOW LINE ; fragment UnicodeClassND : '\\u0030'..'\\u0039' | '\\u0660'..'\\u0669' | '\\u06f0'..'\\u06f9' | '\\u07c0'..'\\u07c9' | '\\u0966'..'\\u096f' | '\\u09e6'..'\\u09ef' | '\\u0a66'..'\\u0a6f' | '\\u0ae6'..'\\u0aef' | '\\u0b66'..'\\u0b6f' | '\\u0be6'..'\\u0bef' | '\\u0c66'..'\\u0c6f' | '\\u0ce6'..'\\u0cef' | '\\u0d66'..'\\u0d6f' | '\\u0de6'..'\\u0def' | '\\u0e50'..'\\u0e59' | '\\u0ed0'..'\\u0ed9' | '\\u0f20'..'\\u0f29' | '\\u1040'..'\\u1049' | '\\u1090'..'\\u1099' | '\\u17e0'..'\\u17e9' | '\\u1810'..'\\u1819' | '\\u1946'..'\\u194f' | '\\u19d0'..'\\u19d9' | '\\u1a80'..'\\u1a89' | '\\u1a90'..'\\u1a99' | '\\u1b50'..'\\u1b59' | '\\u1bb0'..'\\u1bb9' | '\\u1c40'..'\\u1c49' | '\\u1c50'..'\\u1c59' | '\\ua620'..'\\ua629' | '\\ua8d0'..'\\ua8d9' | '\\ua900'..'\\ua909' | '\\ua9d0'..'\\ua9d9' | '\\ua9f0'..'\\ua9f9' | '\\uaa50'..'\\uaa59' | '\\uabf0'..'\\uabf9' | '\\uff10'..'\\uff19' ; ",16342,True,3466.138830767146,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.containers { import flash.display.DisplayObject; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import mx.containers.dividedBoxClasses.BoxDivider; import mx.core.EdgeMetrics; import mx.core.IFlexDisplayObject; import mx.core.IFlexModuleFactory; import mx.core.IInvalidating; import mx.core.IUIComponent; import mx.core.UIComponent; import mx.core.mx_internal; import mx.events.ChildExistenceChangedEvent; import mx.events.DividerEvent; import mx.managers.CursorManager; import mx.managers.CursorManagerPriority; import mx.styles.IStyleManager2; import mx.styles.StyleManager; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched multiple times as the user drags any divider. * * The dividerDrag event is dispatched * after the dividerPress event * and before the dividerRelease event. * * @eventType mx.events.DividerEvent.DIVIDER_DRAG * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerDrag"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user presses any divider in this container. * * The dividerPress event is dispatched * before any dividerDrag events are dispatched. * * @eventType mx.events.DividerEvent.DIVIDER_PRESS * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerPress"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user releases a divider. * * The dividerRelease event is dispatched * after the dividerDrag events, * but before the container's children are resized. * The divider's x and y properties are not updated until * after this event is triggered. As a result, a call to * hDividerBox.getDividerAt(0).x will return * the value of the original x position of the first divider. If you want the * position of the divider after the move, you can access it when the * DividerBox's updateComplete event has been triggered. * * @eventType mx.events.DividerEvent.DIVIDER_RELEASE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerRelease"", type=""mx.events.DividerEvent"")] //-------------------------------------- // Styles //-------------------------------------- /** * Thickness in pixels of the area where the user can click to drag a * divider. * This area is centered in the gaps between the container's children, * which are determined by the horizontalGap or * verticalGap style property. * The affordance cannot be set to a value larger than the gap size. * A resize cursor appears when the mouse is over this area. * * @default 6 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerAffordance"", type=""Number"", format=""Length"", inherit=""no"")] /** * The alpha value that determines the transparency of the dividers. * A value of 0.0 means completely transparent * and a value of 1.0 means completely opaque. * * @default 0.75 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerAlpha"", type=""Number"", inherit=""no"")] /** * Color of the dividers when the user presses or drags the dividers * if the liveDragging property is set to false. * If the liveDragging property is set to true, * only the divider's knob is shown. * * @default 0x6F7777 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerColor"", type=""uint"", format=""Color"", inherit=""yes"")] /** * The divider skin. * * The default value is the ""mx.skin.BoxDividerSkin"" symbol in the Assets.swf file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerSkin"", type=""Class"", inherit=""no"")] /** * Thickness in pixels of the dividers when the user presses or drags the * dividers, if the liveDragging property is set to false. * (If the liveDragging property is set to true, * only the divider's knob is shown.) * The visible thickness cannot be set to a value larger than the affordance. * * @default 3 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerThickness"", type=""Number"", format=""Length"", inherit=""no"")] /** * The cursor skin for a horizontal DividedBox. * * The default value is the ""mx.skins.cursor.HBoxDivider"" symbol in the Assets.swf file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""horizontalDividerCursor"", type=""Class"", inherit=""no"")] /** * The cursor skin for a vertical DividedBox. * * The default value is the ""mx.skins.cursor.VBoxDivider"" symbol in the Assets.swf file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""verticalDividerCursor"", type=""Class"", inherit=""no"")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name=""focusIn"", kind=""event"")] [Exclude(name=""focusOut"", kind=""event"")] [Exclude(name=""focusBlendMode"", kind=""style"")] [Exclude(name=""focusSkin"", kind=""style"")] [Exclude(name=""focusThickness"", kind=""style"")] [Exclude(name=""focusInEffect"", kind=""effect"")] [Exclude(name=""focusOutEffect"", kind=""effect"")] //-------------------------------------- // Other metadata //-------------------------------------- [IconFile(""DividedBox.png"")] /** * A DividedBox container measures and lays out its children * horizontally or vertically in exactly the same way as a * Box container, but it inserts * draggable dividers in the gaps between the children. * Users can drag any divider to resize the children on each side. * *

The DividedBox class is the base class for the more commonly used * HDividedBox and VDividedBox classes.

* *

The direction property of a DividedBox container, inherited * from Box container, determines whether it has horizontal * or vertical layout.

* *

A DividedBox, HDividedBox, or VDividedBox container has the following default sizing characteristics:

* * * * * * * * * * * * * * * * * *
CharacteristicDescription
Default sizeVertical DividedBox Height is large enough to hold all of its children at the default or explicit * heights of the children, plus any vertical gap between the children, plus the top and bottom padding of the * container. The width is the default or explicit width of the widest child, plus the left and right padding of * the container. *
Horizontal DividedBox Width is large enough to hold all of its children at the * default or explicit widths of the children, plus any horizontal gap between the children, plus the left and * right padding of the container. Height is the default or explicit height of the tallest child * plus the top and bottom padding of the container.
Default padding0 pixels for the top, bottom, left, and right values.
Default gap10 pixels for the horizontal and vertical gaps.
* * @mxml * *

The <mx:DividedBox> tag inherits all of the tag * attributes of its superclass, and adds the following tag attributes:

* *
 *  <mx:DividedBox
 *    Properties
 *    liveDragging=""false|true""
 *    resizeToContent=""false|true""
 *  
 *    Styles
 *    dividerAffordance=""6""
 *    dividerAlpha=""0.75""
 *    dividerColor=""0x6F7777""
 *    dividerSkin=""'mx.skins.BoxDividerSkin' symbol in Assets.swf""
 *    dividerThickness=""3""
 *    horizontalDividerCursor=""'mx.skins.cursor.HBoxDivider' symbol in Assets.swf""
 *    verticalDividerCursor=""'mx.skins.cursor.VBoxDivider' symbol in Assets.swf""
 * 
 *    Events
 *    dividerPress=""No default""
 *    dividerDrag=""No default""
 *    dividerRelease=""No default""
 *    >
 *      ...
 *      child tags
 *      ...
 *  </mx:DividedBox>
 *  
* * @see mx.containers.HDividedBox * @see mx.containers.VDividedBox * * @includeExample examples/DividedBoxExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DividedBox extends Box { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private */ private static const PROXY_DIVIDER_INDEX:int = 999; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function DividedBox() { super(); addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler); addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE, childRemoveHandler); // make divided box visible in automation by default because // users interact with the dividers showInAutomationHierarchy = true; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Container for holding divider objects. */ private var dividerLayer:UIComponent = null; /** * @private */ mx_internal var activeDivider:BoxDivider; /** * @private */ private var activeDividerIndex:int = -1; /** * @private */ private var activeDividerStartPosition:Number; /** * @private */ private var dragStartPosition:Number; /** * @private */ private var dragDelta:Number; /** * @private */ private var oldChildSizes:Array /* of ChildSizeInfo */; /** * @private */ private var minDelta:Number; /** * @private */ private var maxDelta:Number; /** * @private * Only allow a single divider to move at a time. */ private var dontCoalesceDividers:Boolean; /** * @private */ private var cursorID:int = CursorManager.NO_CURSOR; /** * @private * We'll measure ourselves once and then store the results here * for the lifetime of the DividedBox. */ private var dbMinWidth:Number; private var dbMinHeight:Number; private var dbPreferredWidth:Number; private var dbPreferredHeight:Number; /** * @private */ private var layoutStyleChanged:Boolean = false; /** * @private */ private var _resizeToContent:Boolean = false; /** * @private * Number of children with their includeInLayout set to true. The rest of * the children don't count. */ private var numLayoutChildren:int = 0; //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- /** * @private */ override public function set moduleFactory(moduleFactory:IFlexModuleFactory):void { super.moduleFactory = moduleFactory; styleManager.registerSizeInvalidatingStyle(""dividerAffordance""); styleManager.registerSizeInvalidatingStyle(""dividerThickness""); } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // direction //---------------------------------- /** * @private */ override public function set direction(value:String):void { if (super.direction != value) { super.direction = value; // Need to invalidate all our dividers if (dividerLayer) { for (var i:int = 0; i < dividerLayer.numChildren; i++) getDividerAt(i).invalidateDisplayList(); } } } //---------------------------------- // dividerClass //---------------------------------- /** * The class for the divider between the children. * * @default mx.containers.dividedBoxClasses.BoxDivider * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var dividerClass:Class = BoxDivider; //---------------------------------- // liveDragging //---------------------------------- [Inspectable(category=""General"")] /** * If true, the children adjacent to a divider * are continuously resized while the user drags it. * If false, they are not resized * until the user releases the divider. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var liveDragging:Boolean = false; //---------------------------------- // numDividers //---------------------------------- /** * The number of dividers. * The count is always numChildren - 1. * * @return The number of dividers. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get numDividers():int { if (dividerLayer) if (!liveDragging && activeDivider) return dividerLayer.numChildren-1; else return dividerLayer.numChildren; else return 0; } //---------------------------------- // resizeToContent //---------------------------------- /** * If true, the DividedBox automatically resizes to the size * of its children. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get resizeToContent():Boolean { return _resizeToContent; } /** * @private */ public function set resizeToContent(value:Boolean):void { if (value != _resizeToContent) { _resizeToContent = value; if (value) invalidateSize(); } } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private * Override of the measure method of Box. * *

This function is almost identical to the Box version except * that more extensive testing of the min, max * boundary conditions is performed. This is because the DividedBox allows * default values to be less than the min value of a control.

*/ override protected function measure():void { super.measure(); // We only measure ourselves once, since as we change the // size of children, they in turn change the preferred sizes // // We need to copy the cached values into the measured fields // again to handle the case where scaleX or scaleY is not 1.0. // When the ViewStack is zoomed, code in UIComponent.measureSizes // scales the measuredWidth/Height values every time that // measureSizes is called. (Bug 100749) if (!isNaN(dbPreferredWidth) && !_resizeToContent && !layoutStyleChanged) { measuredMinWidth = dbMinWidth; measuredMinHeight = dbMinHeight; measuredWidth = dbPreferredWidth; measuredHeight = dbPreferredHeight; return; } layoutStyleChanged = false; var isVertical:Boolean = this.isVertical(); var minWidth:Number = 0; var minHeight:Number = 0; var preferredWidth:Number = 0; var preferredHeight:Number = 0; var n:int = numChildren; for (var i:int = 0; i < n; i++) { var child:IUIComponent = getLayoutChildAt(i); if (!child.includeInLayout) continue; var prefW:Number = child.getExplicitOrMeasuredWidth(); var prefH:Number = child.getExplicitOrMeasuredHeight(); var minW:Number = child.minWidth; var minH:Number = child.minHeight; var wFlex:Boolean = !isNaN(child.percentWidth); var hFlex:Boolean = !isNaN(child.percentHeight); // Make sure we take the lowest of the low, since pref < min. var smallestMinW:Number = Math.min(prefW, minW); var smallestMinH:Number = Math.min(prefH, minH); if (isVertical) { minWidth = Math.max(wFlex ? minW : prefW, minWidth); preferredWidth = Math.max(prefW, preferredWidth); minHeight += hFlex ? smallestMinH : prefH; preferredHeight += prefH; } else { minWidth += wFlex ? smallestMinW : prefW; preferredWidth += prefW; minHeight = Math.max(hFlex ? minH : prefH, minHeight); preferredHeight = Math.max(prefH, preferredHeight); } } var wPadding:Number = layoutObject.widthPadding(numLayoutChildren); var hPadding:Number = layoutObject.heightPadding(numLayoutChildren); measuredMinWidth = dbMinWidth = minWidth + wPadding; measuredMinHeight = dbMinHeight = minHeight + hPadding; measuredWidth = dbPreferredWidth = preferredWidth + wPadding; measuredHeight = dbPreferredHeight = preferredHeight + hPadding; } /** * @private */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { var n:int; var i:int; // This method gets called while dragging a divider, // but we don't want to do anything then. if (!liveDragging && activeDivider) { n = numChildren; for (i = 0; i < n; i++) { var child:IUIComponent = getLayoutChildAt(i); if (!child.includeInLayout) continue; // Clear out measured min/max // so super.layout() doesn't use them. child.measuredMinWidth = 0; child.measuredMinHeight = 0; } return; } // Before we allow layout, let's clear out any measured min // values of our children so that they don't restrict us. // We only honour explicitly set mins/maxs. // We also try to remove any excess space, but tweaking // the % values on the flexible components. preLayoutAdjustment(); // Let Box lay out the children. super.updateDisplayList(unscaledWidth, unscaledHeight); postLayoutAdjustment(); // Lay out the dividers. if (!dividerLayer) return; var vm:EdgeMetrics = viewMetrics; dividerLayer.x = vm.left; dividerLayer.y = vm.top; var prevChild:IUIComponent = null; var dividerIndex:int = 0; n = numChildren; for (i = 0; i < n; i++) { child = UIComponent(getChildAt(i)); if (child.includeInLayout) { if (prevChild) { layoutDivider(dividerIndex, unscaledWidth, unscaledHeight, prevChild, child); dividerIndex++; } prevChild = child; } } } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); // Need to invalidate all our dividers if (dividerLayer) { var n:int = dividerLayer.numChildren; for (var i:int = 0; i < n; i++) { getDividerAt(i).styleChanged(styleProp); } } if (styleManager.isSizeInvalidatingStyle(styleProp)) { layoutStyleChanged = true; } } /** * @private */ override protected function scrollChildren():void { super.scrollChildren(); // Scroll divider layer. if (contentPane && dividerLayer) dividerLayer.scrollRect = contentPane.scrollRect; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Returns a reference to the specified BoxDivider object * in this DividedBox container or null if it doesn't exist. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @return A BoxDivider object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getDividerAt(i:int):BoxDivider { if (dividerLayer) { // Check whether this is a valid divider index. if (i < 0 || i >= dividerLayer.numChildren) return null; else return BoxDivider(dividerLayer.getChildAt(i)); } else { return null; } } /** * Move a specific divider a given number of pixels. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @param amt The number of pixels to move the divider. * A negative number can be specified in order to move * a divider up or left. The divider movement is * constrained in the same manner as if a user * had moved it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function moveDivider(i:int, amt:Number):void { // Check whether this is a valid divider index. if (i < 0 || i >= numDividers) return; // Make sure the user is not currently dragging. if (activeDividerIndex >= 0) return; // We have to first hit the children if we haven't // yet done so since the first movement . // Mimic a divider moving. activeDividerIndex = i; // Store away child sizes, // then determine the limits on our movement. cacheChildSizes(); computeMinAndMaxDelta(); dragDelta = limitDelta(amt); // Now update the children sizes accordingly. adjustChildSizes(); invalidateSize(); invalidateDisplayList(); // Reset the divider tracking stuff. resetDividerTracking(); } /** * @private */ private function createDivider(i:int):BoxDivider { // Create separate layer for holding divider objects. if (!dividerLayer) { dividerLayer = UIComponent(rawChildren.addChild(new UIComponent())); } var divider:BoxDivider = BoxDivider(new dividerClass()); dividerLayer.addChild(divider); // if we are creating the active divider bring the divider layer // to the top most so that users can see the divider line over // the other children if (i == PROXY_DIVIDER_INDEX) { rawChildren.setChildIndex(dividerLayer, rawChildren.numChildren-1); } // Tell BoxDivider to use DividedBox's styles, // unless we are sliding the divider; in that case, // use the styles of the divider we are sliding. var basedOn:IFlexDisplayObject = (i == PROXY_DIVIDER_INDEX) ? getDividerAt(activeDividerIndex) : this; divider.styleName = basedOn; divider.owner = this; return divider; } /** * @private */ private function layoutDivider(i:int, unscaledWidth:Number, unscaledHeight:Number, prevChild:IUIComponent, nextChild:IUIComponent):void { // The mouse-over thickness of the divider is normally determined // by the dividerAffordance style, and the visible thickness is // normally determined by the dividerThickness style, assuming that // the relationship thickness <= affordance <= gap applies. But if // one of the other five orderings applies, here is a table of what // happens: // // divider divider horizontalGap/ dividerWidth/ visible width/ // Thickness Affordance verticalGap dividerHeight visible height // // 4 6 8 6 4 // 4 8 6 6 4 // 6 4 8 6 6 // 6 8 4 4 4 // 8 4 6 6 6 // 8 6 4 4 4 var divider:BoxDivider = BoxDivider(getDividerAt(i)); var vm:EdgeMetrics = viewMetrics; var verticalGap:Number = getStyle(""verticalGap""); var horizontalGap:Number = getStyle(""horizontalGap""); var thickness:Number = divider.getStyle(""dividerThickness""); var affordance:Number = divider.getStyle(""dividerAffordance""); if (isVertical()) { var dividerHeight:Number = affordance; // dividerHeight is the mouse-over height, // not necessarily the visible height. // The specified affordance should be greater than the thickness. // But if it isn't, use the thickness instead to determine the // divider height. if (dividerHeight < thickness) dividerHeight = thickness; // Don't let the divider overlap the children. if (dividerHeight > verticalGap) dividerHeight = verticalGap; divider.setActualSize(unscaledWidth - vm.left - vm.right, dividerHeight); divider.move(vm.left, Math.round((prevChild.y + prevChild.height + nextChild.y - dividerHeight) / 2)); } else { var dividerWidth:Number = affordance; // dividerWidth is the mouse-over width, // not necessarily the visible width. // The specified affordance should be greater than the thickness. // But if it isn't, use the thickness instead to determine the // divider width. if (dividerWidth < thickness) dividerWidth = thickness; // Don't let the divider overlap the children. if (dividerWidth > horizontalGap) dividerWidth = horizontalGap; divider.setActualSize(dividerWidth, unscaledHeight - vm.top - vm.bottom); divider.move(Math.round((prevChild.x + prevChild.width + nextChild.x - dividerWidth) / 2), vm.top); } divider.invalidateDisplayList(); } /** * @private */ mx_internal function changeCursor(divider:BoxDivider):void { if (cursorID == CursorManager.NO_CURSOR) { // If a cursor skin has been set for the specified BoxDivider, // use it. Otherwise, use the cursor skin for the DividedBox. var cursorClass:Class = isVertical() ? getStyle(""verticalDividerCursor"") as Class : getStyle(""horizontalDividerCursor"") as Class; cursorID = cursorManager.setCursor(cursorClass, CursorManagerPriority.HIGH, 0, 0); } } /** * @private */ mx_internal function restoreCursor():void { if (cursorID != CursorManager.NO_CURSOR) { cursorManager.removeCursor(cursorID); cursorID = CursorManager.NO_CURSOR; } } /** * @private */ mx_internal function getDividerIndex(divider:BoxDivider):int { var n:int = numChildren; for (var i:int = 0; i < n - 1; i++) { if (getDividerAt(i) == divider) return i; } return -1; } /** * @private */ private function getMousePosition(event:MouseEvent):Number { var point:Point = new Point(event.stageX, event.stageY); point = globalToLocal(point); return isVertical() ? point.y : point.x; } /** * @private */ mx_internal function startDividerDrag(divider:BoxDivider, trigger:MouseEvent):void { // Make sure the user is not currently dragging. if (activeDividerIndex >= 0) return; activeDividerIndex = getDividerIndex(divider); var event:DividerEvent = new DividerEvent(DividerEvent.DIVIDER_PRESS); event.dividerIndex = activeDividerIndex; dispatchEvent(event); if (liveDragging) activeDivider = divider; else { activeDivider = createDivider(PROXY_DIVIDER_INDEX); activeDivider.visible = false; activeDivider.state = DividerState.DOWN; activeDivider.setActualSize(divider.width, divider.height); activeDivider.move(divider.x, divider.y); activeDivider.visible = true; divider.state = DividerState.UP; } if (isVertical()) activeDividerStartPosition = activeDivider.y; else activeDividerStartPosition = activeDivider.x; dragStartPosition = getMousePosition(trigger); dragDelta = 0; cacheChildSizes(); adjustChildSizes(); computeMinAndMaxDelta(); systemManager.getSandboxRoot().addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); systemManager.deployMouseShields(true); } /** * @private * Store away some important information about * each child for us to use while we move the divider. */ private function cacheSizes():void { oldChildSizes = []; // empty array var vertical:Boolean = isVertical(); var smallest:Number = Number.MAX_VALUE; // use a big number var n:int = numChildren; for (var i:int = 0; i < n; i++) { var child:IUIComponent = getLayoutChildAt(i); if (!child.includeInLayout) continue; var sz:Number = vertical ? child.height : child.width; var mx:Number = vertical ? child.maxHeight : child.maxWidth; var umn:Number = vertical ? child.explicitMinHeight : child.explicitMinWidth; // avoid measured values // A NaN min means 0. var mn:Number = (isNaN(umn)) ? 0 : umn; // Compute these for later use. var dMin:Number = Math.max(0, sz - mn); var dMax:Number = Math.max(0, mx - sz); if (sz > 0 && sz < smallest) smallest = sz; oldChildSizes.push(new ChildSizeInfo(sz, mn, mx, dMin, dMax)); } // Remember the smallest child size we saw. oldChildSizes.push(new ChildSizeInfo((smallest == Number.MAX_VALUE) ? 1 : smallest)); } /** * @private */ private function cacheChildSizes():void { oldChildSizes = []; // clear or store cacheSizes(); } /** * @private */ private function mouseMoveHandler(event:MouseEvent):void { dragDelta = limitDelta(getMousePosition(event) - dragStartPosition); var dividerEvent:DividerEvent = new DividerEvent(DividerEvent.DIVIDER_DRAG); dividerEvent.dividerIndex = activeDividerIndex; dividerEvent.delta = dragDelta; dispatchEvent(dividerEvent); if (liveDragging) { adjustChildSizes(); invalidateDisplayList(); updateDisplayList(unscaledWidth, unscaledHeight); } else { if (isVertical()) activeDivider.move(0, activeDividerStartPosition + dragDelta); else activeDivider.move(activeDividerStartPosition + dragDelta, 0); } } /** * @private * * @param trigger May be null if the event is not a MouseEvent but * a mouse event from another sandbox. */ mx_internal function stopDividerDrag(divider:BoxDivider, trigger:MouseEvent):void { if (trigger) dragDelta = limitDelta(getMousePosition(trigger) - dragStartPosition); var event:DividerEvent = new DividerEvent(DividerEvent.DIVIDER_RELEASE); event.dividerIndex = activeDividerIndex; event.delta = dragDelta; dispatchEvent(event); if (!liveDragging) { if (dragDelta == 0) getDividerAt(activeDividerIndex).state = DividerState.OVER; if (activeDivider) dividerLayer.removeChild(activeDivider); activeDivider = null; adjustChildSizes(); invalidateSize(); invalidateDisplayList(); } resetDividerTracking(); systemManager.getSandboxRoot().removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); systemManager.deployMouseShields(false); } /** * @private */ private function resetDividerTracking():void { activeDivider = null; activeDividerIndex = -1; activeDividerStartPosition = NaN; dragStartPosition = NaN; dragDelta = NaN; oldChildSizes = null; minDelta = NaN; maxDelta = NaN; } /** * @private * Determine the maximum amount of movement that * a divider, i, can move both up and down. * * We base this calculation on the amount of * travel that each divider supports, assuming * that as one divider reaches its limits, the next * divider will move. In this way dividers will * cascade. */ private function computeAllowableMovement(at:int):void { // We break the computation into two loops, // so that we can calc min and max travel // independently as one would move the divider // either up or down. var deltaMinAbove:Number = 0; var deltaMaxAbove:Number = 0; var deltaMinBelow:Number = 0; var deltaMaxBelow:Number = 0; var n:int = numLayoutChildren; var i:int; var child:ChildSizeInfo; if (at < 0) return; for (i = at; i >= 0; i--) { child = ChildSizeInfo(oldChildSizes[i]); deltaMinAbove += (dontCoalesceDividers && deltaMinAbove) ? 0 : child.deltaMin; deltaMaxAbove += (dontCoalesceDividers && deltaMaxAbove) ? 0 : child.deltaMax; } for (i = at + 1; i < n; i++) { child = ChildSizeInfo(oldChildSizes[i]); deltaMinBelow += (dontCoalesceDividers && deltaMinBelow) ? 0 : child.deltaMin; deltaMaxBelow += (dontCoalesceDividers && deltaMaxBelow) ? 0 : child.deltaMax; } // Now the maximum movement we can have if // the divider is moved up is equal to the // smaller of how much we can shrink all // components above our divider or the // maximum of how much the components below // our divider can grow. Similarly for the // divider moving in the opposite direction. var deltaUp:Number = Math.min(deltaMinAbove, deltaMaxBelow); var deltaDn:Number = Math.min(deltaMinBelow, deltaMaxAbove); // deltaUp needs to be in -ve in order for our // update logic to work minDelta = -deltaUp; maxDelta = deltaDn; } /** * @private */ private function computeMinAndMaxDelta():void { computeAllowableMovement(activeDividerIndex); } /** * @private */ private function limitDelta(delta:Number):Number { if (delta < minDelta) delta = minDelta; else if (delta > maxDelta) delta = maxDelta; // Make sure it is not fractional, // otherwise we lose pixels. (Bug 87339) delta = Math.round(delta); return delta; } /** * @private * We distribute the delta space in the same * fashion that we calculated it. That is we * start at the divider and give out space * until we hit a limit on the component or * we run out of space to distribute. * We need to do this in both directions since * in one direction we are shrinking and * in the other we are growing. */ private function distributeDelta():void { // if there is no movement of divider we need not // do any child resizing. if (!dragDelta) return; var vertical:Boolean = isVertical(); var n:int = numLayoutChildren; var k:int = activeDividerIndex; var smallest:Number = oldChildSizes[n].size - Math.abs(dragDelta); // smallest possible child size if (smallest <= 0 || isNaN(smallest)) smallest = 1; var i:int; var size:ChildSizeInfo; var move:Number; var newSize:Number; var child:IUIComponent; var childSize:Number; // Find the index of the child before the active divider var activeDividerChildIndex:int = -1; var dividerIndex:int = -1; while (dividerIndex < activeDividerIndex) { if (UIComponent(getChildAt(++activeDividerChildIndex)).includeInLayout) ++dividerIndex; } // Distribute space starting from the center and // moving upwards. var curChildIndex:int = activeDividerChildIndex; var amt:Number = dragDelta; for (i = k; i >= 0; i--) { // If dragDelta -ve => shrink upper components // otherwise grow them. size = ChildSizeInfo(oldChildSizes[i]); move = (amt < 0) ? -Math.min(-amt, size.deltaMin) : Math.min(amt, size.deltaMax); // Adjust the component and reduce the remaining delta newSize = size.size + move; amt -= move; // Find the previous child included in the layout do { child = IUIComponent(getChildAt(curChildIndex--)); } while (!child.includeInLayout); // Adjust the child size. childSize = (newSize / smallest) * 100; if (vertical) child.percentHeight = childSize; else child.percentWidth = childSize; // Force a re-measure. if (child is IInvalidating) IInvalidating(child).invalidateSize(); } // assert(amt == 0) // Now do the same distribution but moving downwards. curChildIndex = activeDividerChildIndex + 1; amt = dragDelta; for (i = k + 1; i < n; i++) { // If dragDelta -ve => grow lower components // otherwise shrink them. size = ChildSizeInfo(oldChildSizes[i]); move = (amt < 0) ? Math.min(-amt, size.deltaMax) : -Math.min(amt, size.deltaMin); // Adjust the component and reduce the remaining delta. newSize = size.size + move; amt += move; // Find the next child included in the layout do { child = IUIComponent(getChildAt(curChildIndex++)); } while (!child.includeInLayout); childSize = (newSize / smallest) * 100; if (vertical) child.percentHeight = childSize; else child.percentWidth = childSize; // Force a re-measure. if (child is IInvalidating) IInvalidating(child).invalidateSize(); } } /** * @private * For 1.5 we normalize all children to the smallest one * So that we can remove n-1 children and still guarantee * one child can consume 100%. * Also we support the concept of fixed sized children, * which allows us to have one or more children be rigid * in the DividedBox in this case, the dividers above * and below the fixed component move in unison. */ private function adjustChildSizes():void { distributeDelta(); } /** * @private * Algorithm employed pre-layout to ensure that * we don't leave any dangling space and to ensure * that only explicit min/max values are honored. * * We first compute the sum of %'s across all * children to ensure that we have at least 100%. * If so, we are done. If not, then we attempt * to attach the remaining amount to the last * component, if not, then we distribute the * percentages evenly across all % components. * */ private function preLayoutAdjustment():void { // Calculate the total % var vertical:Boolean = isVertical(); var totalPerc:Number = 0; var percCount:Number = 0; var n:int = numChildren; var i:int; var child:IUIComponent; var perc:Number; for (i = 0; i < n; i++) { child = getLayoutChildAt(i); if (!child.includeInLayout) continue; // Clear out measured min/max // so super.layout() doesn't use them. child.measuredMinWidth = 0; child.measuredMinHeight = 0; perc = vertical ? child.percentHeight : child.percentWidth; if (!isNaN(perc)) { totalPerc += perc; percCount++; } } // during preLayoutAdjustment, we make some changes to the children's // widths and heights. We keep track of the original values in postLayoutChanges // so we can later go back and reset them so another layout pass is working // with the correct values rather than these modified values. postLayoutChanges = []; var changeObject:Object; // No flexible children, so we make the last one 100%. if (totalPerc == 0 && percCount == 0) { // Everyone is fixed and we can give 100% to the last // included in layout one without concern. for (i = n-1; i >= 0; i--) { child = UIComponent(getChildAt(i)); if (child.includeInLayout) { // create a changeObject to keep track of the original values // that this child had for width and height changeObject = {child: child}; if (vertical) { // we know there's no percentHeight originally if (child.explicitHeight) changeObject.explicitHeight = child.explicitHeight; else changeObject.percentHeight = NaN; child.percentHeight = 100; } else { // we know there's no percentWidth originally if (child.explicitWidth) changeObject.explicitWidth = child.explicitWidth; else if (child.percentWidth) changeObject.percentWidth = NaN; child.percentWidth = 100; } postLayoutChanges.push(changeObject); break; } } } else if (totalPerc < 100) { // We have some %s but they don't total to 100, so lets // distribute the delta across all of them and in the // meantime normalize all %s to unscaledHeight/Width. // The normalization takes care of the case where any one // of the components hits a min/max limit on their size, // which could result in the others filling less than 100%. var delta:Number = Math.ceil((100 - totalPerc) / percCount); for (i = 0; i < n; i++) { child = getLayoutChildAt(i); if (!child.includeInLayout) continue; changeObject = {child: child}; if (vertical) { perc = child.percentHeight; if (!isNaN(perc)) { changeObject.percentHeight = child.percentHeight; postLayoutChanges.push(changeObject); child.percentHeight = (perc + delta) * unscaledHeight; } } else { perc = child.percentWidth; if (!isNaN(perc)) { changeObject.percentWidth = child.percentWidth; postLayoutChanges.push(changeObject); child.percentWidth = (perc + delta) * unscaledWidth; } } } } // OK after all this magic we still can't guarantee that the space is // entirely filled. For example, all percent components hit their max // values. In this case, the layout will include empty space at the end, // and once the divider is touched, the non-percent based components // will be converted into percent based ones and fill the remaining // space. It seems to me that this scenario is highly unlikely. // Thus I've choosen the route of stretching the percent based // components and not touching the explicitly sized or default // sized ones. // // Another option would be to stretch the default sized components // either in addition to the percent based ones or instead of. // This seemed a little odd to me as the user never indicated // that these components are to be stretched initially, so in the end // I choose to tweak the components that the user has indicated // as being stretchable. } /** * @private * During preLayoutAdjustment, we make some changes to the children's * widths and heights. We keep track of the original values in postLayoutChanges * so we can later go back and reset them so another layout pass is working * with the correct values rather than these modified values. */ private var postLayoutChanges:Array; /** * @private * Post layout work. In preLayoutAdjustment() * sometimes we set a child's percentWidth/percentHeight. * postLayoutAdjustment() will reset the child's width or height * back to what it was. */ private function postLayoutAdjustment():void { // each object has a child property and may have a set of width/height // properties that it would like to be set var len:int = postLayoutChanges.length; for (var i:int = 0; i < len; i++) { var changeObject:Object = postLayoutChanges[i]; if (changeObject.percentWidth !== undefined) changeObject.child.percentWidth = changeObject.percentWidth; if (changeObject.percentHeight !== undefined) changeObject.child.percentHeight = changeObject.percentHeight; if (changeObject.explicitWidth !== undefined) changeObject.child.explicitWidth = changeObject.explicitWidth; if (changeObject.explicitHeight !== undefined) changeObject.child.explicitHeight = changeObject.explicitHeight; } postLayoutChanges = null; } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function childAddHandler(event:ChildExistenceChangedEvent):void { var child:DisplayObject = event.relatedObject; child.addEventListener(""includeInLayoutChanged"", child_includeInLayoutChangedHandler); if (!IUIComponent(child).includeInLayout) return; numLayoutChildren++; if (numLayoutChildren > 1) createDivider(numLayoutChildren - 2); // Clear the cached values so that we do another // measurement pass. dbMinWidth = NaN; dbMinHeight = NaN; dbPreferredWidth = NaN; dbPreferredHeight = NaN; } /** * @private */ private function childRemoveHandler(event:ChildExistenceChangedEvent):void { var child:DisplayObject = event.relatedObject; child.removeEventListener(""includeInLayoutChanged"", child_includeInLayoutChangedHandler); if (!IUIComponent(child).includeInLayout) return; numLayoutChildren--; if (numLayoutChildren > 0) dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // Clear the cached values so that we do another // measurement pass. dbMinWidth = NaN; dbMinHeight = NaN; dbPreferredWidth = NaN; dbPreferredHeight = NaN; invalidateSize(); } /** * @private * When a child's includeInLayout changes, we either remove or add a * divider. */ private function child_includeInLayoutChangedHandler(event:Event):void { var child:UIComponent = UIComponent(event.target); if (child.includeInLayout && ++numLayoutChildren > 1) createDivider(numLayoutChildren - 2); else if (!child.includeInLayout && --numLayoutChildren > 0) dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // Clear the cached values so that we do another // measurement pass. dbMinWidth = NaN; dbMinHeight = NaN; dbPreferredWidth = NaN; dbPreferredHeight = NaN; invalidateSize(); } } } //////////////////////////////////////////////////////////////////////////////// // // Helper class: ChildSizeInfo // //////////////////////////////////////////////////////////////////////////////// /** * @private */ class ChildSizeInfo { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * @private */ public function ChildSizeInfo(size:Number, min:Number = 0, max:Number = 0, deltaMin:Number = 0, deltaMax:Number = 0) { super(); this.size = size; this.min = min; this.max = max; this.deltaMin = deltaMin; this.deltaMax = deltaMax; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // deltaMin //---------------------------------- /** * @private */ public var deltaMin:Number; //---------------------------------- // deltaMax //---------------------------------- /** * @private */ public var deltaMax:Number; //---------------------------------- // min //---------------------------------- /** * @private */ public var min:Number; //---------------------------------- // max //---------------------------------- /** * @private */ public var max:Number; //---------------------------------- // size //---------------------------------- /** * @private */ public var size:Number; } ",12524,False,2099.8112779098915,median "/** * BigInteger * * An ActionScript 3 implementation of BigInteger (light version) * Copyright (c) 2007 Henri Torgemane * * Derived from: * The jsbn library, Copyright (c) 2003-2005 Tom Wu * * See LICENSE.txt for full license information. */ package com.hurlant.math { import com.hurlant.crypto.prng.Random; import com.hurlant.util.Hex; import com.hurlant.util.Memory; import flash.utils.ByteArray; use namespace bi_internal; public class BigInteger { public static const DB:int = 30; // number of significant bits per chunk public static const DV:int = (1<0) { if (p>p)>0) { m = true; r = d.toString(36); } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { r += d.toString(36); } } } return m?r:""0""; } public function toArray(array:ByteArray):uint { const k:int = 8; const km:int = (1<<8)-1; var d:int = 0; var i:int = t; var p:int = DB-(i*DB)%k; var m:Boolean = false; var c:int = 0; if (i-->0) { if (p>p)>0) { m = true; array.writeByte(d); c++; } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { array.writeByte(d); c++; } } } return c; } /** * best-effort attempt to fit into a Number. * precision can be lost if it just can't fit. */ public function valueOf():Number { var coef:Number = 1; var value:Number = 0; for (var i:uint=0;i v, - if this < v, 0 if equal */ public function compareTo(v:BigInteger):int { var r:int = s - v.s; if (r!=0) { return r; } var i:int = t; r = i-v.t; if (r!=0) { return r; } while (--i >=0) { r=a[i]-v.a[i]; if (r != 0) return r; } return 0; } /** * returns bit length of the integer x */ bi_internal function nbits(x:int):int { var r:int = 1; var t:int; if ((t=x>>>16) != 0) { x = t; r += 16; } if ((t=x>>8) != 0) { x = t; r += 8; } if ((t=x>>4) != 0) { x = t; r += 4; } if ((t=x>>2) != 0) { x = t; r += 2; } if ((t=x>>1) != 0) { x = t; r += 1; } return r; } /** * returns the number of bits in this */ public function bitLength():int { if (t<=0) return 0; return DB*(t-1)+nbits(a[t-1]^(s&DM)); } /** * * @param v * @return this % v * */ public function mod(v:BigInteger):BigInteger { var r:BigInteger = nbi(); abs().divRemTo(v,null,r); if (s<0 && r.compareTo(ZERO)>0) { v.subTo(r,r); } return r; } /** * this^e % m, 0 <= e < 2^32 */ public function modPowInt(e:int, m:BigInteger):BigInteger { var z:IReduction; if (e<256 || m.isEven()) { z = new ClassicReduction(m); } else { z = new MontgomeryReduction(m); } return exp(e, z); } /** * copy this to r */ bi_internal function copyTo(r:BigInteger):void { for (var i:int = t-1; i>=0; --i) { r.a[i] = a[i]; } r.t = t; r.s = s; } /** * set from integer value ""value"", -DV <= value < DV */ bi_internal function fromInt(value:int):void { t = 1; s = (value<0)?-1:0; if (value>0) { a[0] = value; } else if (value<-1) { a[0] = value+DV; } else { t = 0; } } /** * set from ByteArray and length, * starting a current position * If length goes beyond the array, pad with zeroes. */ bi_internal function fromArray(value:ByteArray, length:int):void { var p:int = value.position; var i:int = p+length; var sh:int = 0; const k:int = 8; t = 0; s = 0; while (--i >= p) { var x:int = i DB) { a[t-1] |= (x&((1<<(DB-sh))-1))<>(DB-sh); } else { a[t-1] |= x<= DB) sh -= DB; } clamp(); value.position = Math.min(p+length,value.length); } /** * clamp off excess high words */ bi_internal function clamp():void { var c:int = s&DM; while (t>0 && a[t-1]==c) { --t; } } /** * r = this << n*DB */ bi_internal function dlShiftTo(n:int, r:BigInteger):void { var i:int; for (i=t-1; i>=0; --i) { r.a[i+n] = a[i]; } for (i=n-1; i>=0; --i) { r.a[i] = 0; } r.t = t+n; r.s = s; } /** * r = this >> n*DB */ bi_internal function drShiftTo(n:int, r:BigInteger):void { var i:int; for (i=n; i=0; --i) { r.a[i+ds+1] = (a[i]>>cbs)|c; c = (a[i]&bm)<=0; --i) { r.a[i] = 0; } r.a[ds] = c; r.t = t+ds+1; r.s = s; r.clamp(); } /** * r = this >> n */ bi_internal function rShiftTo(n:int, r:BigInteger):void { r.s = s; var ds:int = n/DB; if (ds >= t) { r.t = 0; return; } var bs:int = n%DB; var cbs:int = DB-bs; var bm:int = (1<>bs; var i:int; for (i=ds+1; i>bs; } if (bs>0) { r.a[t-ds-1] |= (s&bm)<>= DB; } if (v.t < t) { c -= v.s; while (i< t) { c+= a[i]; r.a[i++] = c&DM; c >>= DB; } c += s; } else { c += s; while (i < v.t) { c -= v.a[i]; r.a[i++] = c&DM; c >>= DB; } c -= v.s; } r.s = (c<0)?-1:0; if (c<-1) { r.a[i++] = DV+c; } else if (c>0) { r.a[i++] = c; } r.t = i; r.clamp(); } /** * am: Compute w_j += (x*this_i), propagates carries, * c is initial carry, returns final carry. * c < 3*dvalue, x < 2*dvalue, this_i < dvalue */ bi_internal function am(i:int,x:int,w:BigInteger,j:int,c:int,n:int):int { var xl:int = x&0x7fff; var xh:int = x>>15; while(--n >= 0) { var l:int = a[i]&0x7fff; var h:int = a[i++]>>15; var m:int = xh*l + h*xl; l = xl*l + ((m&0x7fff)<<15)+w.a[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w.a[j++] = l&0x3fffffff; } return c; } /** * r = this * v, r != this,a (HAC 14.12) * ""this"" should be the larger one if appropriate */ bi_internal function multiplyTo(v:BigInteger, r:BigInteger):void { var x:BigInteger = abs(); var y:BigInteger = v.abs(); var i:int = x.t; r.t = i+y.t; while (--i >= 0) { r.a[i] = 0; } for (i=0; i=0) r.a[i] = 0; for (i=0; i= DV) { r.a[i+x.t] -= DV; r.a[i+x.t+1] = 1; } } if (r.t>0) { r.a[r.t-1] += x.am(i, x.a[i], r, 2*i, 0, 1); } r.s = 0; r.clamp(); } /** * divide this by m, quotient and remainder to q, r (HAC 14.20) * r != q, this != m. q or r may be null. */ bi_internal function divRemTo(m:BigInteger, q:BigInteger = null, r:BigInteger = null):void { var pm:BigInteger = m.abs(); if (pm.t <= 0) return; var pt:BigInteger = abs(); if (pt.t < pm.t) { if (q!=null) q.fromInt(0); if (r!=null) copyTo(r); return; } if (r==null) r = nbi(); var y:BigInteger = nbi(); var ts:int = s; var ms:int = m.s; var nsh:int = DB-nbits(pm.a[pm.t-1]); // normalize modulus if (nsh>0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys:int = y.t; var y0:int = y.a[ys-1]; if (y0==0) return; var yt:Number = y0*(1<1)?y.a[ys-2]>>F2:0); var d1:Number = FV/yt; var d2:Number = (1<=0) { r.a[r.t++] = 1; r.subTo(t,r); } ONE.dlShiftTo(ys,t); t.subTo(y,y); // ""negative"" y so we can replace sub with am later. while(y.t= 0) { // Estimate quotient digit var qd:int = (r.a[--i]==y0)?DM:Number(r.a[i])*d1+(Number(r.a[i-1])+e)*d2; if ((r.a[i]+= y.am(0, qd, r, j, 0, ys))0) { r.rShiftTo(nsh, r); // Denormalize remainder } if (ts<0) { ZERO.subTo(r,r); } } /** * return ""-1/this % 2^DB""; useful for Mont. reduction * justification: * xy == 1 (mod n) * xy = 1+km * xy(2-xy) = (1+km)(1-km) * x[y(2-xy)] = 1-k^2.m^2 * x[y(2-xy)] == 1 (mod m^2) * if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 * should reduce x and y(2-xy) by m^2 at each step to keep size bounded * [XXX unit test the living shit out of this.] */ bi_internal function invDigit():int { if (t<1) return 0; var x:int = a[0]; if ((x&1)==0) return 0; var y:int = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf )*y)) &0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y)) &0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints // XXX 48 bit ints? Whaaaa? is there an implicit float conversion in here? y = (y*(2-x*y%DV))%DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?DV-y:-y; } /** * true iff this is even */ bi_internal function isEven():Boolean { return ((t>0)?(a[0]&1):s) == 0; } /** * this^e, e < 2^32, doing sqr and mul with ""r"" (HAC 14.79) */ bi_internal function exp(e:int, z:IReduction):BigInteger { if (e > 0xffffffff || e < 1) return ONE; var r:BigInteger = nbi(); var r2:BigInteger = nbi(); var g:BigInteger = z.convert(this); var i:int = nbits(e)-1; g.copyTo(r); while(--i>=0) { z.sqrTo(r, r2); if ((e&(1<0) { z.mulTo(r2,g,r); } else { var t:BigInteger = r; r = r2; r2 = t; } } return z.revert(r); } bi_internal function intAt(str:String, index:int):int { return parseInt(str.charAt(index), 36); } protected function nbi():* { return new BigInteger; } /** * return bigint initialized to value */ public static function nbv(value:int):BigInteger { var bn:BigInteger = new BigInteger; bn.fromInt(value); return bn; } // Functions above are sufficient for RSA encryption. // The stuff below is useful for decryption and key generation public static const lowprimes:Array = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; public static const lplim:int = (1<<26)/lowprimes[lowprimes.length-1]; public function clone():BigInteger { var r:BigInteger = new BigInteger; this.copyTo(r); return r; } /** * * @return value as integer * */ public function intValue():int { if (s<0) { if (t==1) { return a[0]-DV; } else if (t==0) { return -1; } } else if (t==1) { return a[0]; } else if (t==0) { return 0; } // assumes 16 < DB < 32 return ((a[1]&((1<<(32-DB))-1))<>24; } /** * * @return value as short (assumes DB>=16) * */ public function shortValue():int { return (t==0)?s:(a[0]<<16)>>16; } /** * * @param r * @return x s.t. r^x < DV * */ protected function chunkSize(r:Number):int { return Math.floor(Math.LN2*DB/Math.log(r)); } /** * * @return 0 if this ==0, 1 if this >0 * */ public function sigNum():int { if (s<0) { return -1; } else if (t<=0 || (t==1 && a[0]<=0)) { return 0; } else{ return 1; } } /** * * @param b: radix to use * @return a string representing the integer converted to the radix. * */ protected function toRadix(b:uint=10):String { if (sigNum()==0 || b<2 || b>32) return ""0""; var cs:int = chunkSize(b); var a:Number = Math.pow(b, cs); var d:BigInteger = nbv(a); var y:BigInteger = nbi(); var z:BigInteger = nbi(); var r:String = """"; divRemTo(d, y, z); while (y.sigNum()>0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } /** * * @param s a string to convert from using radix. * @param b a radix * */ protected function fromRadix(s:String, b:int = 10):void { fromInt(0); var cs:int = chunkSize(b); var d:Number = Math.pow(b, cs); var mi:Boolean = false; var j:int = 0; var w:int = 0; for (var i:int=0;i= cs) { dMultiply(d); dAddOffset(w,0); j=0; w=0; } } if (j>0) { dMultiply(Math.pow(b,j)); dAddOffset(w,0); } if (mi) { BigInteger.ZERO.subTo(this, this); } } // XXX function fromNumber not written yet. /** * * @return a byte array. * */ public function toByteArray():ByteArray { var i:int = t; var r:ByteArray = new ByteArray; r[0] = s; var p:int = DB-(i*DB)%8; var d:int; var k:int=0; if (i-->0) { if (p>p)!=(s&DM)>>p) { r[k++] = d|(s<<(DB-p)); } while (i>=0) { if(p<8) { d = (a[i]&((1<>(p+=DB-8); } else { d = (a[i]>>(p-=8))&0xff; if (p<=0) { p += DB; --i; } } if ((d&0x80)!=0) d|=-256; if (k==0 && (s&0x80)!=(d&0x80)) ++k; if (k>0 || d!=s) r[k++] = d; } } return r; } public function equals(a:BigInteger):Boolean { return compareTo(a)==0; } public function min(a:BigInteger):BigInteger { return (compareTo(a)<0)?this:a; } public function max(a:BigInteger):BigInteger { return (compareTo(a)>0)?this:a; } /** * * @param a a BigInteger to perform the operation with * @param op a Function implementing the operation * @param r a BigInteger to store the result of the operation * */ protected function bitwiseTo(a:BigInteger, op:Function, r:BigInteger):void { var i:int; var f:int; var m:int = Math.min(a.t, t); for (i=0; i>= 16; r += 16; } if ((x&0xff) == 0) { x>>= 8; r += 8; } if ((x&0xf) == 0) { x>>= 4; r += 4; } if ((x&0x3) == 0) { x>>= 2; r += 2; } if ((x&0x1) == 0) ++r; return r; } /** * * @return index of lowest 1-bit (or -1 if none) * */ public function getLowestSetBit():int { for (var i:int=0;i=t) { return s!=0; } return ((a[j]&(1<<(n%DB)))!=0); } /** * * @param n * @param op * @return this op (1<>=DB; } if (a.t < t) { c += a.s; while (i>= DB; } c += s; } else { c += s; while (i>= DB; } c += a.s; } r.s = (c<0)?-1:0; if (c>0) { r.a[i++] = c; } else if (c<-1) { r.a[i++] = DV+c; } r.t = i; r.clamp(); } /** * * @param a * @return this + a * */ public function add(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; addTo(a,r); return r; } /** * * @param a * @return this - a * */ public function subtract(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; subTo(a,r); return r; } /** * * @param a * @return this * a * */ public function multiply(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; multiplyTo(a,r); return r; } /** * * @param a * @return this / a * */ public function divide(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, r, null); return r; } public function remainder(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, null, r); return r; } /** * * @param a * @return [this/a, this%a] * */ public function divideAndRemainder(a:BigInteger):Array { var q:BigInteger = new BigInteger; var r:BigInteger = new BigInteger; divRemTo(a, q, r); return [q,r]; } /** * * this *= n, this >=0, 1 < n < DV * * @param n * */ bi_internal function dMultiply(n:int):void { a[t] = am(0, n-1, this, 0, 0, t); ++t; clamp(); } /** * * this += n << w words, this >= 0 * * @param n * @param w * */ bi_internal function dAddOffset(n:int, w:int):void { while (t<=w) { a[t++] = 0; } a[w] += n; while (a[w] >= DV) { a[w] -= DV; if (++w >= t) { a[t++] = 0; } ++a[w]; } } /** * * @param e * @return this^e * */ public function pow(e:int):BigInteger { return exp(e, new NullReduction); } /** * * @param a * @param n * @param r = lower n words of ""this * a"", a.t <= n * */ bi_internal function multiplyLowerTo(a:BigInteger, n:int, r:BigInteger):void { var i:int = Math.min(t+a.t, n); r.s = 0; // assumes a, this >= 0 r.t = i; while (i>0) { r.a[--i]=0; } var j:int; for (j=r.t-t;i 0 * */ bi_internal function multiplyUpperTo(a:BigInteger, n:int, r:BigInteger):void { --n; var i:int = r.t = t+a.t-n; r.s = 0; // assumes a,this >= 0 while (--i>=0) { r.a[i] = 0; } for (i=Math.max(n-t,0);i 1) { var g2:BigInteger = new BigInteger; z.sqrTo(g[1], g2); while (n<=km) { g[n] = new BigInteger; z.mulTo(g2, g[n-2], g[n]); n += 2; } } var j:int = e.t-1; var w:int; var is1:Boolean = true; var r2:BigInteger = new BigInteger; var t:BigInteger; i = nbits(e.a[j])-1; while (j>=0) { if (i>=k1) { w = (e.a[j]>>(i-k1))&km; } else { w = (e.a[j]&((1<<(i+1))-1))<<(k1-i); if (j>0) { w |= e.a[j-1]>>(DB+i-k1); } } n = k; while ((w&1)==0) { w >>= 1; --n; } if ((i -= n) <0) { i += DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n>1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n>0) { z.sqrTo(r, r2); } else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j>=0 && (e.a[j]&(1<0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.sigNum()>0) { if ((i = x.getLowestSetBit()) >0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) >0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g>0) { y.lShiftTo(g, y); } return y; } /** * * @param n * @return this % n, n < 2^DB * */ protected function modInt(n:int):int { if (n<=0) return 0; var d:int = DV%n; var r:int = (s<0)?n-1:0; if (t>0) { if (d==0) { r = a[0]%n; } else { for (var i:int=t-1;i>=0;--i) { r = (d*r+a[i])%n; } } } return r; } /** * * @param m * @return 1/this %m (HAC 14.61) * */ public function modInverse(m:BigInteger):BigInteger { var ac:Boolean = m.isEven(); if ((isEven()&&ac) || m.sigNum()==0) { return BigInteger.ZERO; } var u:BigInteger = m.clone(); var v:BigInteger = clone(); var a:BigInteger = nbv(1); var b:BigInteger = nbv(0); var c:BigInteger = nbv(0); var d:BigInteger = nbv(1); while (u.sigNum()!=0) { while (u.isEven()) { u.rShiftTo(1,u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if (!b.isEven()) { b.subTo(m,b); } b.rShiftTo(1,b); } while (v.isEven()) { v.rShiftTo(1,v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if (!d.isEven()) { d.subTo(m,d); } d.rShiftTo(1,d); } if (u.compareTo(v)>=0) { u.subTo(v,u); if (ac) { a.subTo(c,a); } b.subTo(d,b); } else { v.subTo(u,v); if (ac) { c.subTo(a,c); } d.subTo(b,d); } } if (v.compareTo(BigInteger.ONE) != 0) { return BigInteger.ZERO; } if (d.compareTo(m) >= 0) { return d.subtract(m); } if (d.sigNum()<0) { d.addTo(m,d); } else { return d; } if (d.sigNum()<0) { return d.add(m); } else { return d; } } /** * * @param t * @return primality with certainty >= 1-.5^t * */ public function isProbablePrime(t:int):Boolean { var i:int; var x:BigInteger = abs(); if (x.t == 1 && x.a[0]<=lowprimes[lowprimes.length-1]) { for (i=0;i>1; if (t>lowprimes.length) { t = lowprimes.length; } var a:BigInteger = new BigInteger; for (var i:int=0;ibits) subTo(BigInteger.ONE.shiftLeft(bits-1),this); } } } } ",12123,True,2669.974068520357,median "/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package Box2D.Dynamics{ import Box2D.Collision.*; import Box2D.Collision.Shapes.*; import Box2D.Common.*; import Box2D.Common.Math.*; import Box2D.Dynamics.Contacts.*; import Box2D.Dynamics.Controllers.b2Controller; import Box2D.Dynamics.Controllers.b2ControllerEdge; import Box2D.Dynamics.Joints.*; use namespace b2internal; /** * The world class manages all physics entities, dynamic simulation, * and asynchronous queries. */ public class b2World { // Construct a world object. /** * @param gravity the world gravity vector. * @param doSleep improve performance by not simulating inactive bodies. */ public function b2World(gravity:b2Vec2, doSleep:Boolean){ m_destructionListener = null; m_debugDraw = null; m_bodyList = null; m_contactList = null; m_jointList = null; m_controllerList = null; m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; m_controllerCount = 0; m_warmStarting = true; m_continuousPhysics = true; m_allowSleep = doSleep; m_gravity = gravity; m_inv_dt0 = 0.0; m_contactManager.m_world = this; var bd:b2BodyDef = new b2BodyDef(); m_groundBody = CreateBody(bd); } /** * Destruct the world. All physics entities are destroyed and all heap memory is released. */ //~b2World(); /** * Register a destruction listener. */ public function SetDestructionListener(listener:b2DestructionListener) : void{ m_destructionListener = listener; } /** * Register a contact filter to provide specific control over collision. * Otherwise the default filter is used (b2_defaultFilter). */ public function SetContactFilter(filter:b2ContactFilter) : void{ m_contactManager.m_contactFilter = filter; } /** * Register a contact event listener */ public function SetContactListener(listener:b2ContactListener) : void{ m_contactManager.m_contactListener = listener; } /** * Register a routine for debug drawing. The debug draw functions are called * inside the b2World::Step method, so make sure your renderer is ready to * consume draw commands when you call Step(). */ public function SetDebugDraw(debugDraw:b2DebugDraw) : void{ m_debugDraw = debugDraw; } /** * Use the given object as a broadphase. * The old broadphase will not be cleanly emptied. * @warning It is not recommended you call this except immediately after constructing the world. * @warning This function is locked during callbacks. */ public function SetBroadPhase(broadPhase:IBroadPhase) : void { var oldBroadPhase:IBroadPhase = m_contactManager.m_broadPhase; m_contactManager.m_broadPhase = broadPhase; for (var b:b2Body = m_bodyList; b; b = b.m_next) { for (var f:b2Fixture = b.m_fixtureList; f; f = f.m_next) { f.m_proxy = broadPhase.CreateProxy(oldBroadPhase.GetFatAABB(f.m_proxy), f); } } } /** * Perform validation of internal data structures. */ public function Validate() : void { m_contactManager.m_broadPhase.Validate(); } /** * Get the number of broad-phase proxies. */ public function GetProxyCount() : int { return m_contactManager.m_broadPhase.GetProxyCount(); } /** * Create a rigid body given a definition. No reference to the definition * is retained. * @warning This function is locked during callbacks. */ public function CreateBody(def:b2BodyDef) : b2Body{ //b2Settings.b2Assert(m_lock == false); if (IsLocked() == true) { return null; } //void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); var b:b2Body = new b2Body(def, this); // Add to world doubly linked list. b.m_prev = null; b.m_next = m_bodyList; if (m_bodyList) { m_bodyList.m_prev = b; } m_bodyList = b; ++m_bodyCount; return b; } /** * Destroy a rigid body given a definition. No reference to the definition * is retained. This function is locked during callbacks. * @warning This automatically deletes all associated shapes and joints. * @warning This function is locked during callbacks. */ public function DestroyBody(b:b2Body) : void{ //b2Settings.b2Assert(m_bodyCount > 0); //b2Settings.b2Assert(m_lock == false); if (IsLocked() == true) { return; } // Delete the attached joints. var jn:b2JointEdge = b.m_jointList; while (jn) { var jn0:b2JointEdge = jn; jn = jn.next; if (m_destructionListener) { m_destructionListener.SayGoodbyeJoint(jn0.joint); } DestroyJoint(jn0.joint); } // Detach controllers attached to this body var coe:b2ControllerEdge = b.m_controllerList; while (coe) { var coe0:b2ControllerEdge = coe; coe = coe.nextController; coe0.controller.RemoveBody(b); } // Delete the attached contacts. var ce:b2ContactEdge = b.m_contactList; while (ce) { var ce0:b2ContactEdge = ce; ce = ce.next; m_contactManager.Destroy(ce0.contact); } b.m_contactList = null; // Delete the attached fixtures. This destroys broad-phase // proxies. var f:b2Fixture = b.m_fixtureList; while (f) { var f0:b2Fixture = f; f = f.m_next; if (m_destructionListener) { m_destructionListener.SayGoodbyeFixture(f0); } f0.DestroyProxy(m_contactManager.m_broadPhase); f0.Destroy(); //f0->~b2Fixture(); //m_blockAllocator.Free(f0, sizeof(b2Fixture)); } b.m_fixtureList = null; b.m_fixtureCount = 0; // Remove world body list. if (b.m_prev) { b.m_prev.m_next = b.m_next; } if (b.m_next) { b.m_next.m_prev = b.m_prev; } if (b == m_bodyList) { m_bodyList = b.m_next; } --m_bodyCount; //b->~b2Body(); //m_blockAllocator.Free(b, sizeof(b2Body)); } /** * Create a joint to constrain bodies together. No reference to the definition * is retained. This may cause the connected bodies to cease colliding. * @warning This function is locked during callbacks. */ public function CreateJoint(def:b2JointDef) : b2Joint{ //b2Settings.b2Assert(m_lock == false); var j:b2Joint = b2Joint.Create(def, null); // Connect to the world list. j.m_prev = null; j.m_next = m_jointList; if (m_jointList) { m_jointList.m_prev = j; } m_jointList = j; ++m_jointCount; // Connect to the bodies' doubly linked lists. j.m_edgeA.joint = j; j.m_edgeA.other = j.m_bodyB; j.m_edgeA.prev = null; j.m_edgeA.next = j.m_bodyA.m_jointList; if (j.m_bodyA.m_jointList) j.m_bodyA.m_jointList.prev = j.m_edgeA; j.m_bodyA.m_jointList = j.m_edgeA; j.m_edgeB.joint = j; j.m_edgeB.other = j.m_bodyA; j.m_edgeB.prev = null; j.m_edgeB.next = j.m_bodyB.m_jointList; if (j.m_bodyB.m_jointList) j.m_bodyB.m_jointList.prev = j.m_edgeB; j.m_bodyB.m_jointList = j.m_edgeB; var bodyA:b2Body = def.bodyA; var bodyB:b2Body = def.bodyB; // If the joint prevents collisions, then flag any contacts for filtering. if (def.collideConnected == false ) { var edge:b2ContactEdge = bodyB.GetContactList(); while (edge) { if (edge.other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge.contact.FlagForFiltering(); } edge = edge.next; } } // Note: creating a joint doesn't wake the bodies. return j; } /** * Destroy a joint. This may cause the connected bodies to begin colliding. * @warning This function is locked during callbacks. */ public function DestroyJoint(j:b2Joint) : void{ //b2Settings.b2Assert(m_lock == false); var collideConnected:Boolean = j.m_collideConnected; // Remove from the doubly linked list. if (j.m_prev) { j.m_prev.m_next = j.m_next; } if (j.m_next) { j.m_next.m_prev = j.m_prev; } if (j == m_jointList) { m_jointList = j.m_next; } // Disconnect from island graph. var bodyA:b2Body = j.m_bodyA; var bodyB:b2Body = j.m_bodyB; // Wake up connected bodies. bodyA.SetAwake(true); bodyB.SetAwake(true); // Remove from body 1. if (j.m_edgeA.prev) { j.m_edgeA.prev.next = j.m_edgeA.next; } if (j.m_edgeA.next) { j.m_edgeA.next.prev = j.m_edgeA.prev; } if (j.m_edgeA == bodyA.m_jointList) { bodyA.m_jointList = j.m_edgeA.next; } j.m_edgeA.prev = null; j.m_edgeA.next = null; // Remove from body 2 if (j.m_edgeB.prev) { j.m_edgeB.prev.next = j.m_edgeB.next; } if (j.m_edgeB.next) { j.m_edgeB.next.prev = j.m_edgeB.prev; } if (j.m_edgeB == bodyB.m_jointList) { bodyB.m_jointList = j.m_edgeB.next; } j.m_edgeB.prev = null; j.m_edgeB.next = null; b2Joint.Destroy(j, null); //b2Settings.b2Assert(m_jointCount > 0); --m_jointCount; // If the joint prevents collisions, then flag any contacts for filtering. if (collideConnected == false) { var edge:b2ContactEdge = bodyB.GetContactList(); while (edge) { if (edge.other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge.contact.FlagForFiltering(); } edge = edge.next; } } } /** * Add a controller to the world list */ public function AddController(c:b2Controller) : b2Controller { c.m_next = m_controllerList; c.m_prev = null; m_controllerList = c; c.m_world = this; m_controllerCount++; return c; } public function RemoveController(c:b2Controller) : void { //TODO: Remove bodies from controller if (c.m_prev) c.m_prev.m_next = c.m_next; if (c.m_next) c.m_next.m_prev = c.m_prev; if (m_controllerList == c) m_controllerList = c.m_next; m_controllerCount--; } public function CreateController(controller:b2Controller):b2Controller { if (controller.m_world != this) throw new Error(""Controller can only be a member of one world""); controller.m_next = m_controllerList; controller.m_prev = null; if (m_controllerList) m_controllerList.m_prev = controller; m_controllerList = controller; ++m_controllerCount; controller.m_world = this; return controller; } public function DestroyController(controller:b2Controller):void { //b2Settings.b2Assert(m_controllerCount > 0); controller.Clear(); if (controller.m_next) controller.m_next.m_prev = controller.m_prev; if (controller.m_prev) controller.m_prev.m_next = controller.m_next; if (controller == m_controllerList) m_controllerList = controller.m_next; --m_controllerCount; } /** * Enable/disable warm starting. For testing. */ public function SetWarmStarting(flag: Boolean) : void { m_warmStarting = flag; } /** * Enable/disable continuous physics. For testing. */ public function SetContinuousPhysics(flag: Boolean) : void { m_continuousPhysics = flag; } /** * Get the number of bodies. */ public function GetBodyCount() : int { return m_bodyCount; } /** * Get the number of joints. */ public function GetJointCount() : int { return m_jointCount; } /** * Get the number of contacts (each may have 0 or more contact points). */ public function GetContactCount() : int { return m_contactCount; } /** * Change the global gravity vector. */ public function SetGravity(gravity: b2Vec2): void { m_gravity = gravity; } /** * Get the global gravity vector. */ public function GetGravity():b2Vec2{ return m_gravity; } /** * The world provides a single static ground body with no collision shapes. * You can use this to simplify the creation of joints and static shapes. */ public function GetGroundBody() : b2Body{ return m_groundBody; } private static var s_timestep2:b2TimeStep = new b2TimeStep(); /** * Take a time step. This performs collision detection, integration, * and constraint solution. * @param timeStep the amount of time to simulate, this should not vary. * @param velocityIterations for the velocity constraint solver. * @param positionIterations for the position constraint solver. */ public function Step(dt:Number, velocityIterations:int, positionIterations:int) : void{ if (m_flags & e_newFixture) { m_contactManager.FindNewContacts(); m_flags &= ~e_newFixture; } m_flags |= e_locked; var step:b2TimeStep = s_timestep2; step.dt = dt; step.velocityIterations = velocityIterations; step.positionIterations = positionIterations; if (dt > 0.0) { step.inv_dt = 1.0 / dt; } else { step.inv_dt = 0.0; } step.dtRatio = m_inv_dt0 * dt; step.warmStarting = m_warmStarting; // Update contacts. m_contactManager.Collide(); // Integrate velocities, solve velocity constraints, and integrate positions. if (step.dt > 0.0) { Solve(step); } // Handle TOI events. if (m_continuousPhysics && step.dt > 0.0) { SolveTOI(step); } if (step.dt > 0.0) { m_inv_dt0 = step.inv_dt; } m_flags &= ~e_locked; } /** * Call this after you are done with time steps to clear the forces. You normally * call this after each call to Step, unless you are performing sub-steps. */ public function ClearForces() : void { for (var body:b2Body = m_bodyList; body; body = body.m_next) { body.m_force.SetZero(); body.m_torque = 0.0; } } static private var s_xf:b2Transform = new b2Transform(); /** * Call this to draw shapes and other debug draw data. */ public function DrawDebugData() : void{ if (m_debugDraw == null) { return; } m_debugDraw.m_sprite.graphics.clear(); var flags:uint = m_debugDraw.GetFlags(); var i:int; var b:b2Body; var f:b2Fixture; var s:b2Shape; var j:b2Joint; var bp:IBroadPhase; var invQ:b2Vec2 = new b2Vec2; var x1:b2Vec2 = new b2Vec2; var x2:b2Vec2 = new b2Vec2; var xf:b2Transform; var b1:b2AABB = new b2AABB(); var b2:b2AABB = new b2AABB(); var vs:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2(), new b2Vec2()]; // Store color here and reuse, to reduce allocations var color:b2Color = new b2Color(0, 0, 0); if (flags & b2DebugDraw.e_shapeBit) { for (b = m_bodyList; b; b = b.m_next) { xf = b.m_xf; for (f = b.GetFixtureList(); f; f = f.m_next) { s = f.GetShape(); if (b.IsActive() == false) { color.Set(0.5, 0.5, 0.3); DrawShape(s, xf, color); } else if (b.GetType() == b2Body.b2_staticBody) { color.Set(0.5, 0.9, 0.5); DrawShape(s, xf, color); } else if (b.GetType() == b2Body.b2_kinematicBody) { color.Set(0.5, 0.5, 0.9); DrawShape(s, xf, color); } else if (b.IsAwake() == false) { color.Set(0.6, 0.6, 0.6); DrawShape(s, xf, color); } else { color.Set(0.9, 0.7, 0.7); DrawShape(s, xf, color); } } } } if (flags & b2DebugDraw.e_jointBit) { for (j = m_jointList; j; j = j.m_next) { DrawJoint(j); } } if (flags & b2DebugDraw.e_controllerBit) { for (var c:b2Controller = m_controllerList; c; c = c.m_next) { c.Draw(m_debugDraw); } } if (flags & b2DebugDraw.e_pairBit) { color.Set(0.3, 0.9, 0.9); for (var contact:b2Contact = m_contactManager.m_contactList; contact; contact = contact.GetNext()) { var fixtureA:b2Fixture = contact.GetFixtureA(); var fixtureB:b2Fixture = contact.GetFixtureB(); var cA:b2Vec2 = fixtureA.GetAABB().GetCenter(); var cB:b2Vec2 = fixtureB.GetAABB().GetCenter(); m_debugDraw.DrawSegment(cA, cB, color); } } if (flags & b2DebugDraw.e_aabbBit) { bp = m_contactManager.m_broadPhase; vs = [new b2Vec2(),new b2Vec2(),new b2Vec2(),new b2Vec2()]; for (b= m_bodyList; b; b = b.GetNext()) { if (b.IsActive() == false) { continue; } for (f = b.GetFixtureList(); f; f = f.GetNext()) { var aabb:b2AABB = bp.GetFatAABB(f.m_proxy); vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); m_debugDraw.DrawPolygon(vs, 4, color); } } } if (flags & b2DebugDraw.e_centerOfMassBit) { for (b = m_bodyList; b; b = b.m_next) { xf = s_xf; xf.R = b.m_xf.R; xf.position = b.GetWorldCenter(); m_debugDraw.DrawTransform(xf); } } } /** * Query the world for all fixtures that potentially overlap the * provided AABB. * @param callback a user implemented callback class. It should match signature * function Callback(fixture:b2Fixture):Boolean * Return true to continue to the next fixture. * @param aabb the query box. */ public function QueryAABB(callback:Function, aabb:b2AABB):void { var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; function WorldQueryWrapper(proxy:*):Boolean { return callback(broadPhase.GetUserData(proxy)); } broadPhase.Query(WorldQueryWrapper, aabb); } /** * Query the world for all fixtures that precisely overlap the * provided transformed shape. * @param callback a user implemented callback class. It should match signature * function Callback(fixture:b2Fixture):Boolean * Return true to continue to the next fixture. * @asonly */ public function QueryShape(callback:Function, shape:b2Shape, transform:b2Transform = null):void { if (transform == null) { transform = new b2Transform(); transform.SetIdentity(); } var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; function WorldQueryWrapper(proxy:*):Boolean { var fixture:b2Fixture = broadPhase.GetUserData(proxy) as b2Fixture if(b2Shape.TestOverlap(shape, transform, fixture.GetShape(), fixture.GetBody().GetTransform())) return callback(fixture); return true; } var aabb:b2AABB = new b2AABB(); shape.ComputeAABB(aabb, transform); broadPhase.Query(WorldQueryWrapper, aabb); } /** * Query the world for all fixtures that contain a point. * @param callback a user implemented callback class. It should match signature * function Callback(fixture:b2Fixture):Boolean * Return true to continue to the next fixture. * @asonly */ public function QueryPoint(callback:Function, p:b2Vec2):void { var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; function WorldQueryWrapper(proxy:*):Boolean { var fixture:b2Fixture = broadPhase.GetUserData(proxy) as b2Fixture if(fixture.TestPoint(p)) return callback(fixture); return true; } // Make a small box. var aabb:b2AABB = new b2AABB(); aabb.lowerBound.Set(p.x - b2Settings.b2_linearSlop, p.y - b2Settings.b2_linearSlop); aabb.upperBound.Set(p.x + b2Settings.b2_linearSlop, p.y + b2Settings.b2_linearSlop); broadPhase.Query(WorldQueryWrapper, aabb); } /** * Ray-cast the world for all fixtures in the path of the ray. Your callback * Controls whether you get the closest point, any point, or n-points * The ray-cast ignores shapes that contain the starting point * @param callback A callback function which must be of signature: * function Callback(fixture:b2Fixture, // The fixture hit by the ray * point:b2Vec2, // The point of initial intersection * normal:b2Vec2, // The normal vector at the point of intersection * fraction:Number // The fractional length along the ray of the intersection * ):Number * * Callback should return the new length of the ray as a fraction of the original length. * By returning 0, you immediately terminate. * By returning 1, you continue with the original ray. * By returning the current fraction, you proceed to find the closest point. * @param point1 the ray starting point * @param point2 the ray ending point */ public function RayCast(callback:Function, point1:b2Vec2, point2:b2Vec2):void { var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; var output:b2RayCastOutput = new b2RayCastOutput; function RayCastWrapper(input:b2RayCastInput, proxy:*):Number { var userData:* = broadPhase.GetUserData(proxy); var fixture:b2Fixture = userData as b2Fixture; var hit:Boolean = fixture.RayCast(output, input); if (hit) { var fraction:Number = output.fraction; var point:b2Vec2 = new b2Vec2( (1.0 - fraction) * point1.x + fraction * point2.x, (1.0 - fraction) * point1.y + fraction * point2.y); return callback(fixture, point, output.normal, fraction); } return input.maxFraction; } var input:b2RayCastInput = new b2RayCastInput(point1, point2); broadPhase.RayCast(RayCastWrapper, input); } public function RayCastOne(point1:b2Vec2, point2:b2Vec2):b2Fixture { var result:b2Fixture; function RayCastOneWrapper(fixture:b2Fixture, point:b2Vec2, normal:b2Vec2, fraction:Number):Number { result = fixture; return fraction; } RayCast(RayCastOneWrapper, point1, point2); return result; } public function RayCastAll(point1:b2Vec2, point2:b2Vec2):Vector. { var result:Vector. = new Vector.(); function RayCastAllWrapper(fixture:b2Fixture, point:b2Vec2, normal:b2Vec2, fraction:Number):Number { result[result.length] = fixture; return 1; } RayCast(RayCastAllWrapper, point1, point2); return result; } /** * Get the world body list. With the returned body, use b2Body::GetNext to get * the next body in the world list. A NULL body indicates the end of the list. * @return the head of the world body list. */ public function GetBodyList() : b2Body{ return m_bodyList; } /** * Get the world joint list. With the returned joint, use b2Joint::GetNext to get * the next joint in the world list. A NULL joint indicates the end of the list. * @return the head of the world joint list. */ public function GetJointList() : b2Joint{ return m_jointList; } /** * Get the world contact list. With the returned contact, use b2Contact::GetNext to get * the next contact in the world list. A NULL contact indicates the end of the list. * @return the head of the world contact list. * @warning contacts are */ public function GetContactList():b2Contact { return m_contactList; } /** * Is the world locked (in the middle of a time step). */ public function IsLocked():Boolean { return (m_flags & e_locked) > 0; } //--------------- Internals Below ------------------- // Internal yet public to make life easier. // Find islands, integrate and solve constraints, solve position constraints private var s_stack:Vector. = new Vector.(); b2internal function Solve(step:b2TimeStep) : void{ var b:b2Body; // Step all controllers for(var controller:b2Controller= m_controllerList;controller;controller=controller.m_next) { controller.Step(step); } // Size the island for the worst case. var island:b2Island = m_island; island.Initialize(m_bodyCount, m_contactCount, m_jointCount, null, m_contactManager.m_contactListener, m_contactSolver); // Clear all the island flags. for (b = m_bodyList; b; b = b.m_next) { b.m_flags &= ~b2Body.e_islandFlag; } for (var c:b2Contact = m_contactList; c; c = c.m_next) { c.m_flags &= ~b2Contact.e_islandFlag; } for (var j:b2Joint = m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } // Build and simulate all awake islands. var stackSize:int = m_bodyCount; //b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); var stack:Vector. = s_stack; for (var seed:b2Body = m_bodyList; seed; seed = seed.m_next) { if (seed.m_flags & b2Body.e_islandFlag ) { continue; } if (seed.IsAwake() == false || seed.IsActive() == false) { continue; } // The seed can be dynamic or kinematic. if (seed.GetType() == b2Body.b2_staticBody) { continue; } // Reset island and stack. island.Clear(); var stackCount:int = 0; stack[stackCount++] = seed; seed.m_flags |= b2Body.e_islandFlag; // Perform a depth first search (DFS) on the constraint graph. while (stackCount > 0) { // Grab the next body off the stack and add it to the island. b = stack[--stackCount]; //b2Assert(b.IsActive() == true); island.AddBody(b); // Make sure the body is awake. if (b.IsAwake() == false) { b.SetAwake(true); } // To keep islands as small as possible, we don't // propagate islands across static bodies. if (b.GetType() == b2Body.b2_staticBody) { continue; } var other:b2Body; // Search all contacts connected to this body. for (var ce:b2ContactEdge = b.m_contactList; ce; ce = ce.next) { // Has this contact already been added to an island? if (ce.contact.m_flags & b2Contact.e_islandFlag) { continue; } // Is this contact solid and touching? if (ce.contact.IsSensor() == true || ce.contact.IsEnabled() == false || ce.contact.IsTouching() == false) { continue; } island.AddContact(ce.contact); ce.contact.m_flags |= b2Contact.e_islandFlag; //var other:b2Body = ce.other; other = ce.other; // Was the other body already added to this island? if (other.m_flags & b2Body.e_islandFlag) { continue; } //b2Settings.b2Assert(stackCount < stackSize); stack[stackCount++] = other; other.m_flags |= b2Body.e_islandFlag; } // Search all joints connect to this body. for (var jn:b2JointEdge = b.m_jointList; jn; jn = jn.next) { if (jn.joint.m_islandFlag == true) { continue; } other = jn.other; // Don't simulate joints connected to inactive bodies. if (other.IsActive() == false) { continue; } island.AddJoint(jn.joint); jn.joint.m_islandFlag = true; if (other.m_flags & b2Body.e_islandFlag) { continue; } //b2Settings.b2Assert(stackCount < stackSize); stack[stackCount++] = other; other.m_flags |= b2Body.e_islandFlag; } } island.Solve(step, m_gravity, m_allowSleep); // Post solve cleanup. for (var i:int = 0; i < island.m_bodyCount; ++i) { // Allow static bodies to participate in other islands. b = island.m_bodies[i]; if (b.GetType() == b2Body.b2_staticBody) { b.m_flags &= ~b2Body.e_islandFlag; } } } //m_stackAllocator.Free(stack); for (i = 0; i < stack.length;++i) { if (!stack[i]) break; stack[i] = null; } // Synchronize fixutres, check for out of range bodies. for (b = m_bodyList; b; b = b.m_next) { if (b.IsAwake() == false || b.IsActive() == false) { continue; } if (b.GetType() == b2Body.b2_staticBody) { continue; } // Update fixtures (for broad-phase). b.SynchronizeFixtures(); } // Look for new contacts. m_contactManager.FindNewContacts(); } private static var s_backupA:b2Sweep = new b2Sweep(); private static var s_backupB:b2Sweep = new b2Sweep(); private static var s_timestep:b2TimeStep = new b2TimeStep(); private static var s_queue:Vector. = new Vector.(); // Find TOI contacts and solve them. b2internal function SolveTOI(step:b2TimeStep) : void{ var b:b2Body; var fA:b2Fixture; var fB:b2Fixture; var bA:b2Body; var bB:b2Body; var cEdge:b2ContactEdge; var j:b2Joint; // Reserve an island and a queue for TOI island solution. var island:b2Island = m_island; island.Initialize(m_bodyCount, b2Settings.b2_maxTOIContactsPerIsland, b2Settings.b2_maxTOIJointsPerIsland, null, m_contactManager.m_contactListener, m_contactSolver); //Simple one pass queue //Relies on the fact that we're only making one pass //through and each body can only be pushed/popped one. //To push: // queue[queueStart+queueSize++] = newElement; //To pop: // poppedElement = queue[queueStart++]; // --queueSize; var queue:Vector. = s_queue; for (b = m_bodyList; b; b = b.m_next) { b.m_flags &= ~b2Body.e_islandFlag; b.m_sweep.t0 = 0.0; } var c:b2Contact; for (c = m_contactList; c; c = c.m_next) { // Invalidate TOI c.m_flags &= ~(b2Contact.e_toiFlag | b2Contact.e_islandFlag); } for (j = m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } // Find TOI events and solve them. for (;;) { // Find the first TOI. var minContact:b2Contact = null; var minTOI:Number = 1.0; for (c = m_contactList; c; c = c.m_next) { // Can this contact generate a solid TOI contact? if (c.IsSensor() == true || c.IsEnabled() == false || c.IsContinuous() == false) { continue; } // TODO_ERIN keep a counter on the contact, only respond to M TOIs per contact. var toi:Number = 1.0; if (c.m_flags & b2Contact.e_toiFlag) { // This contact has a valid cached TOI. toi = c.m_toi; } else { // Compute the TOI for this contact. fA = c.m_fixtureA; fB = c.m_fixtureB; bA = fA.m_body; bB = fB.m_body; if ((bA.GetType() != b2Body.b2_dynamicBody || bA.IsAwake() == false) && (bB.GetType() != b2Body.b2_dynamicBody || bB.IsAwake() == false)) { continue; } // Put the sweeps onto the same time interval. var t0:Number = bA.m_sweep.t0; if (bA.m_sweep.t0 < bB.m_sweep.t0) { t0 = bB.m_sweep.t0; bA.m_sweep.Advance(t0); } else if (bB.m_sweep.t0 < bA.m_sweep.t0) { t0 = bA.m_sweep.t0; bB.m_sweep.Advance(t0); } //b2Settings.b2Assert(t0 < 1.0f); // Compute the time of impact. toi = c.ComputeTOI(bA.m_sweep, bB.m_sweep); b2Settings.b2Assert(0.0 <= toi && toi <= 1.0); // If the TOI is in range ... if (toi > 0.0 && toi < 1.0) { // Interpolate on the actual range. //toi = Math.min((1.0 - toi) * t0 + toi, 1.0); toi = (1.0 - toi) * t0 + toi; if (toi > 1) toi = 1; } c.m_toi = toi; c.m_flags |= b2Contact.e_toiFlag; } if (Number.MIN_VALUE < toi && toi < minTOI) { // This is the minimum TOI found so far. minContact = c; minTOI = toi; } } if (minContact == null || 1.0 - 100.0 * Number.MIN_VALUE < minTOI) { // No more TOI events. Done! break; } // Advance the bodies to the TOI. fA = minContact.m_fixtureA; fB = minContact.m_fixtureB; bA = fA.m_body; bB = fB.m_body; s_backupA.Set(bA.m_sweep); s_backupB.Set(bB.m_sweep); bA.Advance(minTOI); bB.Advance(minTOI); // The TOI contact likely has some new contact points. minContact.Update(m_contactManager.m_contactListener); minContact.m_flags &= ~b2Contact.e_toiFlag; // Is the contact solid? if (minContact.IsSensor() == true || minContact.IsEnabled() == false) { // Restore the sweeps bA.m_sweep.Set(s_backupA); bB.m_sweep.Set(s_backupB); bA.SynchronizeTransform(); bB.SynchronizeTransform(); continue; } // Did numerical issues prevent;,ontact pointjrom being generated if (minContact.IsTouching() == false) { // Give up on this TOI continue; } // Build the TOI island. We need a dynamic seed. var seed:b2Body = bA; if (seed.GetType() != b2Body.b2_dynamicBody) { seed = bB; } // Reset island and queue. island.Clear(); var queueStart:int = 0; //start index for queue var queueSize:int = 0; //elements in queue queue[queueStart + queueSize++] = seed; seed.m_flags |= b2Body.e_islandFlag; // Perform a breadth first search (BFS) on the contact graph. while (queueSize > 0) { // Grab the next body off the stack and add it to the island. b = queue[queueStart++]; --queueSize; island.AddBody(b); // Make sure the body is awake. if (b.IsAwake() == false) { b.SetAwake(true); } // To keep islands as small as possible, we don't // propagate islands across static or kinematic bodies. if (b.GetType() != b2Body.b2_dynamicBody) { continue; } // Search all contacts connected to this body. for (cEdge = b.m_contactList; cEdge; cEdge = cEdge.next) { // Does the TOI island still have space for contacts? if (island.m_contactCount == island.m_contactCapacity) { break; } // Has this contact already been added to an island? if (cEdge.contact.m_flags & b2Contact.e_islandFlag) { continue; } // Skip sperate, sensor, or disabled contacts. if (cEdge.contact.IsSensor() == true || cEdge.contact.IsEnabled() == false || cEdge.contact.IsTouching() == false) { continue; } island.AddContact(cEdge.contact); cEdge.contact.m_flags |= b2Contact.e_islandFlag; // Update other body. var other:b2Body = cEdge.other; // Was the other body already added to this island? if (other.m_flags & b2Body.e_islandFlag) { continue; } // Synchronize the connected body. if (other.GetType() != b2Body.b2_staticBody) { other.Advance(minTOI); other.SetAwake(true); } //b2Settings.b2Assert(queueStart + queueSize < queueCapacity); queue[queueStart + queueSize] = other; ++queueSize; other.m_flags |= b2Body.e_islandFlag; } for (var jEdge:b2JointEdge = b.m_jointList; jEdge; jEdge = jEdge.next) { if (island.m_jointCount == island.m_jointCapacity) continue; if (jEdge.joint.m_islandFlag == true) continue; other = jEdge.other; if (other.IsActive() == false) { continue; } island.AddJoint(jEdge.joint); jEdge.joint.m_islandFlag = true; if (other.m_flags & b2Body.e_islandFlag) continue; // Synchronize the connected body. if (other.GetType() != b2Body.b2_staticBody) { other.Advance(minTOI); other.SetAwake(true); } //b2Settings.b2Assert(queueStart + queueSize < queueCapacity); queue[queueStart + queueSize] = other; ++queueSize; other.m_flags |= b2Body.e_islandFlag; } } var subStep:b2TimeStep = s_timestep; subStep.warmStarting = false; subStep.dt = (1.0 - minTOI) * step.dt; subStep.inv_dt = 1.0 / subStep.dt; subStep.dtRatio = 0.0; subStep.velocityIterations = step.velocityIterations; subStep.positionIterations = step.positionIterations; island.SolveTOI(subStep); var i:int; // Post solve cleanup. for (i = 0; i < island.m_bodyCount; ++i) { // Allow bodies to participate in future TOI islands. b = island.m_bodies[i]; b.m_flags &= ~b2Body.e_islandFlag; if (b.IsAwake() == false) { continue; } if (b.GetType() != b2Body.b2_dynamicBody) { continue; } // Update fixtures (for broad-phase). b.SynchronizeFixtures(); // Invalidate all contact TOIs associated with this body. Some of these // may not be in the island because they were not touching. for (cEdge = b.m_contactList; cEdge; cEdge = cEdge.next) { cEdge.contact.m_flags &= ~b2Contact.e_toiFlag; } } for (i = 0; i < island.m_contactCount; ++i) { // Allow contacts to participate in future TOI islands. c = island.m_contacts[i]; c.m_flags &= ~(b2Contact.e_toiFlag | b2Contact.e_islandFlag); } for (i = 0; i < island.m_jointCount;++i) { // Allow joints to participate in future TOI islands j = island.m_joints[i]; j.m_islandFlag = false; } // Commit fixture proxy movements to the broad-phase so that new contacts are created. // Also, some contacts can be destroyed. m_contactManager.FindNewContacts(); } //m_stackAllocator.Free(queue); } static private var s_jointColor:b2Color = new b2Color(0.5, 0.8, 0.8); // b2internal function DrawJoint(joint:b2Joint) : void{ var b1:b2Body = joint.GetBodyA(); var b2:b2Body = joint.GetBodyB(); var xf1:b2Transform = b1.m_xf; var xf2:b2Transform = b2.m_xf; var x1:b2Vec2 = xf1.position; var x2:b2Vec2 = xf2.position; var p1:b2Vec2 = joint.GetAnchorA(); var p2:b2Vec2 = joint.GetAnchorB(); //b2Color color(0.5f, 0.8f, 0.8f); var color:b2Color = s_jointColor; switch (joint.m_type) { case b2Joint.e_distanceJoint: m_debugDraw.DrawSegment(p1, p2, color); break; case b2Joint.e_pulleyJoint: { var pulley:b2PulleyJoint = (joint as b2PulleyJoint); var s1:b2Vec2 = pulley.GetGroundAnchorA(); var s2:b2Vec2 = pulley.GetGroundAnchorB(); m_debugDraw.DrawSegment(s1, p1, color); m_debugDraw.DrawSegment(s2, p2, color); m_debugDraw.DrawSegment(s1, s2, color); } break; case b2Joint.e_mouseJoint: m_debugDraw.DrawSegment(p1, p2, color); break; default: if (b1 != m_groundBody) m_debugDraw.DrawSegment(x1, p1, color); m_debugDraw.DrawSegment(p1, p2, color); if (b2 != m_groundBody) m_debugDraw.DrawSegment(x2, p2, color); } } b2internal function DrawShape(shape:b2Shape, xf:b2Transform, color:b2Color) : void{ switch (shape.m_type) { case b2Shape.e_circleShape: { var circle:b2CircleShape = (shape as b2CircleShape); var center:b2Vec2 = b2Math.MulX(xf, circle.m_p); var radius:Number = circle.m_radius; var axis:b2Vec2 = xf.R.col1; m_debugDraw.DrawSolidCircle(center, radius, axis, color); } break; case b2Shape.e_polygonShape: { var i:int; var poly:b2PolygonShape = (shape as b2PolygonShape); var vertexCount:int = poly.GetVertexCount(); var localVertices:Vector. = poly.GetVertices(); var vertices:Vector. = new Vector.(vertexCount); for (i = 0; i < vertexCount; ++i) { vertices[i] = b2Math.MulX(xf, localVertices[i]); } m_debugDraw.DrawSolidPolygon(vertices, vertexCount, color); } break; case b2Shape.e_edgeShape: { var edge: b2EdgeShape = shape as b2EdgeShape; m_debugDraw.DrawSegment(b2Math.MulX(xf, edge.GetVertex1()), b2Math.MulX(xf, edge.GetVertex2()), color); } break; } } b2internal var m_flags:int; b2internal var m_contactManager:b2ContactManager = new b2ContactManager(); // These two are stored purely for efficiency purposes, they don't maintain // any data outside of a call to Step private var m_contactSolver:b2ContactSolver = new b2ContactSolver(); private var m_island:b2Island = new b2Island(); b2internal var m_bodyList:b2Body; private var m_jointList:b2Joint; b2internal var m_contactList:b2Contact; private var m_bodyCount:int; b2internal var m_contactCount:int; private var m_jointCount:int; private var m_controllerList:b2Controller; private var m_controllerCount:int; private var m_gravity:b2Vec2; private var m_allowSleep:Boolean; b2internal var m_groundBody:b2Body; private var m_destructionListener:b2DestructionListener; private var m_debugDraw:b2DebugDraw; // This is used to compute the time step ratio to support a variable time step. private var m_inv_dt0:Number; // This is for debugging the solver. static private var m_warmStarting:Boolean; // This is for debugging the solver. static private var m_continuousPhysics:Boolean; // m_flags public static const e_newFixture:int = 0x0001; public static const e_locked:int = 0x0002; }; } ",12182,False,2248.835863655616,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar SqlBase; tokens { DELIMITER } @header { using Qsi.Data; using Qsi.Tree; using Qsi.Utilities; } singleStatement : statement EOF ; standaloneExpression : expression EOF ; standaloneRoutineBody : routineBody EOF ; /*** * Athena SQL statements follows Hive and Presto SQL statements. * 1. View DDL statements follow Presto. * 2. Other DDL statements follow Hive. * 3. DML statements follow Presto. */ statement /*** * Athena DDL * * @athena (Amazon Athena DDL Reference)[https://docs.aws.amazon.com/athena/latest/ug/language-reference.html] * @hive (HiveQL DDL Reference)[https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL] */ /********************** * * * * * Database DDL * * * * * **********************/ /** * Create Database * * @athena https://docs.aws.amazon.com/athena/latest/ug/create-database.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateDatabaseCreateDatabase */ : CREATE (REMOTE)? (DATABASE | SCHEMA) (IF NOT EXISTS)? databaseName=identifier[null] (COMMENT comment=string)? (LOCATION location=string)? (MANAGEDLOCATION managedLocation=string)? (WITH DBPROPERTIES dbProperties=stringProperties)? #createDatabase /** * Drop Database * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropDatabase */ | DROP (DATABASE | SCHEMA) (IF EXISTS)? databaseName=qualifiedName (RESTRICT | CASCADE)? #dropDatabase /** * Database Set DB Properties * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-database-set-dbproperties.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterDatabase */ | ALTER (DATABASE | SCHEMA) databaseName=qualifiedName SET DBPROPERTIES dbProperties=stringProperties #setDbProperties /** * Database Set Owner * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Database Set Location * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Database Set Managed Location * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Use Database * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-UseDatabase * @notsupport Tested at 2021. 12. 20. */ // | USE // databaseName=identifier[null] #useDatabase /********************** * * * * * Data Connector DDL * * * * * **********************/ /** * Create Connector * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateDataConnectorCreateConnector * @notsupport */ // Not Implemented /** * Drop Connector * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropConnector * @notsupport */ // Not Implemented /** * Connector Set DC Properties * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterConnector * @notsupport */ // Not Implemented /** * Connector Set URL * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterConnector * @notsupport */ // Not Implemented /** * Connector Set Owner * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterConnector * @notsupport */ // Not Implemented /********************** * * * * * Table DDL * * * * * **********************/ /** * Create Table * * @athena https://docs.aws.amazon.com/athena/latest/ug/create-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateTable */ | CREATE (TEMPORARY)? (EXTERNAL)? TABLE (IF NOT EXISTS)? tableName=qualifiedName ( '(' columnDefinition (',' columnDefinition)* ')' )? (COMMENT tableComment=string)? (PARTITIONED BY '(' columnDefinition (',' columnDefinition)* ')' )? ( CLUSTERED BY '(' identifier[null] (',' identifier[null])* ')' (SORTED BY (columnName=identifier[null] (ASC | DESC)? (',' columnName=identifier[null] (ASC | DESC)? )* ) )? INTO numBuckets=number BUCKETS )? ( SKEWED BY '(' columnName=identifier[null] (',' columnName=identifier[null])* ')' ON '(' '(' columnValue=string (',' columnValue=string)* ')' ( ',' '(' columnValue=string (',' columnValue=string)* ')' )* ')' (STORED AS DIRECTORIES)? )? ( ROW FORMAT rowFormat | STORED AS fileFormat | ROW FORMAT rowFormat STORED AS fileFormat | STORED BY storageHandlerClassName=string (WITH SERDEPROPERTIES serDeProperties=stringProperties)? )? (LOCATION location=string)? (TBLPROPERTIES tblProperties=stringProperties)? #createTable /** * Create Table As * * @athena https://docs.aws.amazon.com/athena/latest/ug/create-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateTable */ | CREATE (TEMPORARY)? (EXTERNAL)? TABLE (IF NOT EXISTS)? tableName=qualifiedName ( '(' columnDefinition (',' columnDefinition)* ')' )? (COMMENT tableComment=string)? (PARTITIONED BY '(' columnDefinition (',' columnDefinition)* ')' )? ( CLUSTERED BY '(' identifier[null] (',' identifier[null])* ')' (SORTED BY (columnName=identifier[null] (ASC | DESC)? (',' columnName=identifier[null] (ASC | DESC)? )* ) )? INTO numBuckets=number BUCKETS )? ( SKEWED BY '(' columnName=identifier[null] (',' columnName=identifier[null])* ')' ON '(' '(' columnValue=string (',' columnValue=string)* ')' ( ',' '(' columnValue=string (',' columnValue=string)* ')' )* ')' (STORED AS DIRECTORIES)? )? ( ROW FORMAT rowFormat | STORED AS fileFormat | ROW FORMAT rowFormat STORED AS fileFormat | STORED BY storageHandlerClassName=string (WITH SERDEPROPERTIES serDeProperties=stringProperties)? )? (LOCATION location=string)? (TBLPROPERTIES tblProperties=stringProperties)? AS query (WITH NO? DATA)? #createTableAs /** * Create TABLE LIKE * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateTable */ | CREATE (TEMPORARY)? (EXTERNAL)? TABLE (IF NOT EXISTS)? tableName=qualifiedName LIKE likeTableName=qualifiedName (LOCATION location=string) #createTableLike /** * Drop Table * * @athena https://docs.aws.amazon.com/athena/latest/ug/drop-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropTable */ | DROP TABLE (IF NOT EXISTS)? tableName=qualifiedName (PURGE)? #dropTable /** * Truncate Table * * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /** * Table Rename to * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Set Tbl Properties * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-set-tblproperties.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterTableProperties */ | ALTER TABLE tableName=qualifiedName SET TBLPROPERTIES tblProperties=stringProperties #setTblProperties /** * Table Set Serde * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table Set Serde Properties * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table Unset Serde Properties * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table Add Constraint * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table Clustered by * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Not Clustered * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Skewed by * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Set Skewed Location * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Not Skewed * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Not Stored * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Not Stored as Directories * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Msck Repair Table * * @athena https://docs.aws.amazon.com/athena/latest/ug/msck-repair-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-RecoverPartitions(MSCKREPAIRTABLE) */ | MSCK (REPAIR)? TABLE tableName=qualifiedName (ADD | DROP | SYNC PARTITIONS) #repairTable /*************************** * * * * * Table/Partition DDL * * * * * ***************************/ /** * Table/Partition Set File Format * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table/Partition Touch * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table/Partition Compact * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table/Partition Concatenate * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table/Partition Enable/Disable No Drop * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table/Partition Enable/Disable Offline * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table/Partition Update Columns * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table/Partition Set Location * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-set-location.html * @hive https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=82706445#LanguageManualDDL-AlterTable/PartitionLocation */ | ALTER TABLE tableName=qualifiedName (PARTITION partitionSpec=properties)? SET LOCATION location=string #setLocation /********************** * * * * * Partition DDL * * * * * **********************/ /** * Archive Partition * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Unarchive Partition * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Add Partitions * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-add-partition.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AddPartitions */ | ALTER TABLE tableName=qualifiedName ADD (IF NOT EXISTS)? ( PARTITION partitionSpec=properties (LOCATION location=string)? )+ #addPartitions /** * Rename Partition * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-rename-partition.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-RenamePartition */ | ALTER TABLE tableName=qualifiedName PARTITION from=properties RENAME TO PARTITION to=properties #renamePartition /** * Exchange Partition * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Drop Partition * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-drop-partition.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropPartitions */ | ALTER TABLE tableName=qualifiedName DROP (IF EXISTS)? PARTITION partitionSpec=properties (',' PARTITION partitionSpec=properties)* (IGNORE PROTECTION)? (PURGE)? #dropPartition /********************** * * * * * Column DDL * * * * * **********************/ /** * Change Column * @comment According to Reference 1(AWS), CHANGE COLUMN is not supported in Athena, but works in test * test query: ""ALTER TABLE table_name CHANGE original_column changed_column int"" * * @athena https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ChangeColumnName/Type/Position/Comment */ | ALTER TABLE tableName=qualifiedName (PARTITION properties)? CHANGE (COLUMN)? identifier[null] columnDefinition (FIRST | AFTER identifier[null])? (CASCADE | RESTRICT)? #changeColumn /** * Add Columns * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-add-columns.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-Add/ReplaceColumns */ | ALTER TABLE tableName=qualifiedName (PARTITION partitionSpec=properties)? ADD COLUMNS '(' columnDefinition (',' columnDefinition)* ')' (CASCADE|RESTRICT)? #addColumns /** * Replace Columns * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-replace-columns.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-Add/ReplaceColumns */ | ALTER TABLE tableName=qualifiedName (PARTITION partitionSpec=properties)? REPLACE COLUMNS '(' columnDefinition (',' columnDefinition)* ')' (CASCADE|RESTRICT)? #replaceColumns /********************** * * * * * View DDL * * * * * **********************/ /** * Create View * * @athena https://docs.aws.amazon.com/athena/latest/ug/create-view.html * @presto https://prestodb.io/docs/current/sql/create-view.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateView */ | CREATE (OR REPLACE)? VIEW (IF NOT EXISTS)? viewName=qualifiedName ( columnName=identifier[null] (COMMENT columnComment=string)? (',' columnName=identifier[null] (COMMENT columnComment=string)? )* )? viewColumnAliases? (SECURITY (DEFINER | INVOKER))? (COMMENT viewComment=string)? (TBLPROPERTIES tblProperties=stringProperties)? AS query #createView /** * Drop View * * @athena https://docs.aws.amazon.com/athena/latest/ug/drop-view.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropView */ | DROP VIEW (IF EXISTS)? viewName=qualifiedName #dropView /** * Set View Tbl Properties * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterViewProperties */ | ALTER VIEW viewName=qualifiedName SET TBLPROPERTIES tblProperties=stringProperties #setViewTblProperties /** * Alter View As Select * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterViewAsSelect */ | ALTER VIEW viewName=qualifiedName AS query #alterViewAsSelect /************************* * * * * * Materialized View DDL * * * * * *************************/ /** * Create Materialized View * * @notsupport Not tested */ // Not Implemented /** * Drop Materialized View * * @notsupport Not tested */ // Not Implemented /** * Alter Materialized View * * @notsupport Not tested */ // Not Implemented /************************* * * * * * Index DDL * * * * * *************************/ /** * Create Index * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Drop Index * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Alter Index * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /************************* * * * * * Macro DDL * * * * * *************************/ /** * Create Temporary Macro * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Drop Temporary Macro * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /************************* * * * * * Function DDL * * * * * *************************/ /** * Create Function * * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /** * Drop Function * * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /** * Reload Function * * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /************************* * * * * * Role DDL * * * * * *************************/ /** * Create Role * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Grant Role * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Revoke Role * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Drop Role * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Roles * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Role Grant * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Current Roles * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Set Role * * @notsupport Not tested */ // Not Implemented /** * Show Principals * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Grant privilege_type * * @notsupport Not tested */ // Not Implemented /** * Revoke privilege_type * * @notsupport Not tested */ // Not Implemented /** * Show Grant * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /************************* * * * * * Show DDL * * * * * *************************/ /** * Show Databases * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-databases.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowDatabases */ | SHOW (DATABASES | SCHEMAS) (LIKE string)? #showDatabases /** * Show Connectors * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowConnectors * @notsupport Not tested */ // Not Implemented /** * Show Tables * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-tables.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowTables */ | SHOW TABLES (IN databaseName=identifier[null])? (string)? #showTables /** * Show Views * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-views.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowViews */ | SHOW VIEWS ( (IN | FROM) databaseName=identifier[null])? (LIKE string) #showViews /** * Show Materialized Views * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowMaterializedViews * @notsupport Not tested */ // Not Implemented /** * Show Partitions * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-partitions.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowPartitions */ | SHOW PARTITIONS tableName=qualifiedName (PARTITION properties)? (WHERE where=booleanExpression)? (ORDER BY sortItem (',' sortItem)*)? (LIMIT limit=INTEGER_VALUE)? #showPartitions /** * Show Table/Partition Extended * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowTable/PartitionExtended */ | SHOW TABLE EXTENDED ((IN | FROM) databaseName=qualifiedName)? LIKE string (PARTITION properties)? #showTableExtended /** * Show Table Properties * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-tblproperties.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowTableProperties */ | SHOW TBLPROPERTIES tableName=qualifiedName ( '(' string ')' )? #showTableProperties /** * Show Create Table * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-create-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowCreateTable */ | SHOW CREATE TABLE tableName=qualifiedName #showCreateTable /** * Show Indexes * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowIndexes * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Columns * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-columns.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowColumns */ | SHOW COLUMNS (FROM | IN) tableName=qualifiedName ( (FROM | IN) databaseName=qualifiedName?) (LIKE string)? #showColumns /** * Show Functions * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowFunctions * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Locks * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowLocks * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Conf * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowConf * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /** * Show Transactions * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowTransactions * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Compactions * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowCompactions * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /************************* * * * * * Describe DDL * * * * * *************************/ /** * Describe Database * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DescribeDatabase * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Describe Data Connector * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DescribeDataconnector * @notsupport Not tested */ // Not Implemented /** * Describe Table / View / MaterializedView / Column * * @athena https://docs.aws.amazon.com/athena/latest/ug/describe-table.html * @athena https://docs.aws.amazon.com/athena/latest/ug/describe-view.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DescribeTable/View/MaterializedView/Column */ | (DESCRIBE | DESC) (EXTENDED | FORMATTED)? tableName=qualifiedName (PARTITION partitionSpec=properties)? ( columnName=identifier[null] ( '.' (fieldName=identifier[null] | '$elem$' | '$key$' | '$value$') )* )? #describeTable /************************* * * * * * Abort DDL * * * * * *************************/ /** * Abort Transactions * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AbortTransactions * @notsupport Not tested */ /******************************************************************************************************************/ /** * Athena DML * * @athena (Amazon Athena DML Reference)[https://docs.aws.amazon.com/athena/latest/ug/functions-operators-reference-section.html] * @presto (Presto SQL Syntax Refrence)[https://prestodb.io/docs/current/sql.html] */ /** * ALTER FUNCTION * * @presto https://prestodb.io/docs/current/sql/alter-function.html * @notsupport Use hive syntax */ // Not Implemented /** * ALTER SCHEMA * * @presto https://prestodb.io/docs/current/sql/alter-schema.html * @notsupport Use hive syntax */ // Not Implemented /** * ALTER TABLE * * @presto https://prestodb.io/docs/current/sql/alter-table.html * @notsupport Use hive syntax */ // Not Implemented /** * Analyze * * @presto https://prestodb.io/docs/current/sql/analyze.html * @notsupport Tested at 2021. 12. 20. */ // Not Implemented /** * Call * * @presto https://prestodb.io/docs/current/sql/call.html * @notsupport Tested at 2021. 12. 20. */ // Not Implemented /** * COMMIT * * @presto https://prestodb.io/docs/current/sql/commit.html * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemeneted /** * CREATE FUNCTION * * @presto https://prestodb.io/docs/current/sql/create-function.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE ROLE * * @presto https://prestodb.io/docs/current/sql/create-role.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE SCHEMA * * @presto https://prestodb.io/docs/current/sql/create-schema.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE TABLE * * @presto https://prestodb.io/docs/current/sql/create-table.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE TABLE AS * * @presto https://prestodb.io/docs/current/sql/create-table-as.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE VIEW * * @presto https://prestodb.io/docs/current/sql/create-view.html * @notsupport Use hive syntax */ // Not Implemented /** * DEALLOCATE PREPARE * * @athena https://docs.aws.amazon.com/athena/latest/ug/querying-with-prepared-statements.html * @presto https://prestodb.io/docs/current/sql/deallocate-prepare.html */ | DEALLOCATE PREPARE identifier[null] #deallocate /** * DELETE * * @presto https://prestodb.io/docs/current/sql/delete.html * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * DESCRIBE * * @presto https://prestodb.io/docs/current/sql/describe.html * @notsupport Use hive syntax */ // Not Implemented /** * DESCRIBE INPUT * * @presto https://prestodb.io/docs/current/sql/describe-input.html * @notsupport Use hive syntax */ // Not Implemented /** * DESCRIBE OUTPUT * * @presto https://prestodb.io/docs/current/sql/describe-output.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP FUNCTION * * @presto https://prestodb.io/docs/current/sql/drop-function.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP ROLE * * @presto https://prestodb.io/docs/current/sql/drop-role.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP SCHEMA * * @presto https://prestodb.io/docs/current/sql/drop-schema.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP TABLE * * @presto https://prestodb.io/docs/current/sql/drop-table.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP VIEW * * @presto https://prestodb.io/docs/current/sql/drop-view.html * @notsupport Use hive syntax */ // Not Implemented /** * EXECUTE * * @athena https://docs.aws.amazon.com/athena/latest/ug/querying-with-prepared-statements.html * @presto https://prestodb.io/docs/current/sql/execute.html */ | EXECUTE identifier[null] (USING expression (',' expression)*)? #execute /** * EXPLAIN * * @athena https://docs.aws.amazon.com/athena/latest/ug/athena-explain-statement.html * @presto https://prestodb.io/docs/current/sql/explain.html */ | EXPLAIN VERBOSE? ('(' explainOption (',' explainOption)* ')')? statement #explain /** * EXPLAIN ANALYZE * * @athena https://docs.aws.amazon.com/athena/latest/ug/athena-explain-statement.html * @presto https://prestodb.io/docs/current/sql/explain-analyze.html */ | EXPLAIN ANALYZE VERBOSE? ('(' explainOption (',' explainOption)* ')')? statement #explainAnalyze /** * GRANT * * @presto https://prestodb.io/docs/current/sql/grant.html * @notsupport Use hive syntax */ // Not Implemented /** * GRANT ROLES * * @presto https://prestodb.io/docs/current/sql/grant-roles.html * @notsupport Use hive syntax */ // Not Implemented /** * INSERT * * @athena https://docs.aws.amazon.com/athena/latest/ug/insert-into.html * @presto https://prestodb.io/docs/current/sql/insert.html */ | INSERT INTO qualifiedName columnAliases? query #insertInto /** * PREPARE * * @athena https://docs.aws.amazon.com/athena/latest/ug/querying-with-prepared-statements.html * @presto */ | PREPARE identifier[null] FROM statement #prepare /** * RESET SESSION * * @presto https://prestodb.io/docs/current/sql/reset-session.html * @notsupport Use hive syntax */ // Not Implemented /** * REVOKE * * @presto https://prestodb.io/docs/current/sql/revoke.html * @notsupport Use hive syntax */ // Not Implemented /** * REVOKE ROLES * * @presto https://prestodb.io/docs/current/sql/revoke-roles.html * @notsupport Use hive syntax */ // Not Implemented /** * ROLLBACK * * @presto https://prestodb.io/docs/current/sql/rollback.html * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * SELECT * * @athena https://docs.aws.amazon.com/athena/latest/ug/select.html * @presto https://prestodb.io/docs/current/sql/select.html */ | query #statementDefault /** * SET ROLE * * @presto https://prestodb.io/docs/current/sql/set-role.html * @notsupport Use hive syntax */ // Not Implemented /** * SET SESSION * * @presto https://prestodb.io/docs/current/sql/set-session.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW CATALOGS * * @presto https://prestodb.io/docs/current/sql/show-catalogs.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW COLUMNS * * @presto https://prestodb.io/docs/current/sql/show-columns.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW CREATE FUNCTION * * @presto https://prestodb.io/docs/current/sql/show-create-function.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW CREATE TABLE * * @presto https://prestodb.io/docs/current/sql/show-create-table.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW CREATE VIEW * * @presto https://prestodb.io/docs/current/sql/show-create-view.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW FUNCTIONS * * @presto https://prestodb.io/docs/current/sql/show-functions.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW GRANTS * * @presto https://prestodb.io/docs/current/sql/show-grants.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW ROLE GRANTS * * @presto https://prestodb.io/docs/current/sql/show-role-grants.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW ROLES * * @presto https://prestodb.io/docs/current/sql/show-roles.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW SCHEMAS * * @presto https://prestodb.io/docs/current/sql/show-schemas.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW SESSION * * @presto https://prestodb.io/docs/current/sql/show-session.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW STATS * * @presto https://prestodb.io/docs/current/sql/show-stats.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW TABLES * * @presto https://prestodb.io/docs/current/sql/show-tables.html * @notsupport Use hive syntax */ // Not Implemented /** * START TRANSACTION * * @presto https://prestodb.io/docs/current/sql/start-transaction.html * @notsupport Use hive syntax */ // Not Implemented /** * USE * * @presto https://prestodb.io/docs/current/sql/use.html * @notsupport Use hive syntax */ // Not Implemented /** * VALUES * * @presto https://prestodb.io/docs/current/sql/values.html */ // Implemented in ""query"" /******************************************************************************************************************/ /** * Athena Only Statements */ /** * UNLOAD * * @athena https://docs.aws.amazon.com/athena/latest/ug/unload.html */ | UNLOAD '(' query ')' TO location=string WITH properties #unload ; query : with? queryNoWith ; with : WITH namedQuery (',' namedQuery)* ; //tableElement // : columnDefinition // | likeClause // ; columnDefinition : identifier[null] dataType (COMMENT comment=string)? ; //likeClause // : LIKE qualifiedName (optionType=(INCLUDING | EXCLUDING) PROPERTIES)? // ; rowFormat : DELIMITED (FIELDS TERMINATED BY string (ESCAPED BY string)?)? (COLLECTION ITEMS TERMINATED BY string)? (MAP KEYS TERMINATED BY string)? (LINES TERMINATED BY string)? (NULL DEFINED AS string)? | SERDE string (WITH SERDEPROPERTIES stringProperties)? ; fileFormat : SEQUENCEFILE | TEXTFILE | RCFILE | ORC | PARQUET | AVRO | JSONFILE | INPUTFORMAT string OUTPUTFORMAT string ; stringProperties : '(' stringProperty (',' stringProperty)* ')' ; stringProperty : string EQ string ; properties : '(' property (',' property)* ')' ; property : identifier[null] EQ expression ; //sqlParameterDeclaration // : identifier[null] type // ; //routineCharacteristics // : routineCharacteristic* // ; //routineCharacteristic // : LANGUAGE language // | determinism // | nullCallClause // ; //alterRoutineCharacteristics // : alterRoutineCharacteristic* // ; //alterRoutineCharacteristic // : nullCallClause // ; routineBody : returnStatement | externalBodyReference ; returnStatement : RETURN expression ; externalBodyReference : EXTERNAL (NAME externalRoutineName)? ; //language // : SQL // | identifier[null] // ; // //determinism // : DETERMINISTIC // | NOT DETERMINISTIC; // //nullCallClause // : RETURNS NULL ON NULL INPUT // | CALLED ON NULL INPUT // ; externalRoutineName : identifier[null] ; queryNoWith : queryTerm orderBy? limitOffsetTerm? ; limitOffsetTerm : offsetTerm limitTerm | offsetTerm | limitTerm ; offsetTerm : OFFSET rowCountTerm ROW? | OFFSET rowCountTerm ROWS ; limitTerm : LIMIT rowCountTerm | LIMIT ALL ; rowCountTerm : INTEGER_VALUE | parameterExpression ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm operator=(UNION | EXCEPT | INTERSECT) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | TABLE qualifiedName #table | VALUES expression (',' expression)* #inlineTable | '(' queryNoWith ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrdering=(FIRST | LAST))? ; querySpecification : SELECT setQuantifier? selectItem (',' selectItem)* fromTerm? whereTerm? groupByHavingTerm? ; fromTerm : FROM relation (',' relation)* ; whereTerm : WHERE where=booleanExpression ; groupByHavingTerm : GROUP BY setQuantifier? groupingElement (',' groupingElement)* HAVING having=booleanExpression | GROUP BY setQuantifier? groupingElement (',' groupingElement)* | HAVING having=booleanExpression ; //groupBy // : setQuantifier? groupingElement (',' groupingElement)* // ; groupingElement : groupingSet #singleGroupingSet | ROLLUP '(' (expression (',' expression)*)? ')' #rollup | CUBE '(' (expression (',' expression)*)? ')' #cube | GROUPING SETS '(' groupingSet (',' groupingSet)* ')' #multipleGroupingSets ; groupingSet : '(' (expression (',' expression)*)? ')' #multipleExpressionGroupingSet | expression #singleExpressionGroupingSet ; namedQuery : name=identifier[null] (columnAliases)? AS '(' query ')' ; setQuantifier : DISTINCT | ALL ; selectItem : expression (AS? identifier[null])? #selectSingle | qualifiedName '.' ASTERISK #selectAll | ASTERISK #selectAll ; relation : left=relation ( CROSS JOIN right=sampledRelation | joinType JOIN rightRelation=relation joinCriteria | NATURAL joinType JOIN right=sampledRelation ) #joinRelation | sampledRelation #relationDefault ; joinType : INNER? | LEFT OUTER? | RIGHT OUTER? | FULL OUTER? ; joinCriteria : ON booleanExpression | USING '(' identifier[null] (',' identifier[null])* ')' ; sampledRelation : aliasedRelation ( TABLESAMPLE sampleType '(' percentage=expression ')' )? ; sampleType : BERNOULLI | SYSTEM ; aliasedRelation : relationPrimary (AS? identifier[null] columnAliases?)? ; viewColumnAliases : '(' columnName+=identifier[null] (COMMENT string)? (',' columnName+=identifier[null] (COMMENT string)? )* ')' ; columnAliases : '(' identifier[null] (',' identifier[null])* ')' ; relationPrimary : qualifiedName #tableName | '(' query ')' #subqueryRelation | UNNEST '(' expression (',' expression)* ')' (WITH ORDINALITY)? #unnest | LATERAL '(' query ')' #lateral | '(' relation ')' #parenthesizedRelation ; expression : booleanExpression ; booleanExpression : valueExpression predicate[$valueExpression.ctx]? #predicated | NOT booleanExpression #logicalNot | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; // workaround for https://github.com/antlr/antlr4/issues/780 predicate[ParserRuleContext value] : comparisonOperator right=valueExpression #comparison | comparisonOperator comparisonQuantifier '(' query ')' #quantifiedComparison | NOT? BETWEEN lower=valueExpression AND upper=valueExpression #between | NOT? IN '(' expression (',' expression)* ')' #inList | NOT? IN '(' query ')' #inSubquery | NOT? LIKE pattern=valueExpression (ESCAPE escape=valueExpression)? #like | IS NOT? NULL #nullPredicate | IS NOT? DISTINCT FROM right=valueExpression #distinctFrom ; valueExpression : primaryExpression #valueExpressionDefault | valueExpression AT timeZoneSpecifier #atTimeZone | operator=(MINUS | PLUS) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS) right=valueExpression #arithmeticBinary | left=valueExpression CONCAT right=valueExpression #concatenation ; primaryExpression : NULL #nullLiteral | interval #intervalLiteral | identifier[null] string #typeConstructor | DOUBLE_PRECISION string #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | string #stringLiteral | BINARY_LITERAL #binaryLiteral | parameterExpression #parameter | POSITION '(' valueExpression IN valueExpression ')' #position | '(' expression (',' expression)+ ')' #rowConstructor | ROW '(' expression (',' expression)* ')' #rowConstructor | qualifiedName '(' ASTERISK ')' filter? over? #functionCall | qualifiedName '(' (setQuantifier? expression (',' expression)*)? orderBy? ')' filter? (nullTreatment? over)? #functionCall | identifier[null] '->' expression #lambda | '(' (identifier[null] (',' identifier[null])*)? ')' '->' expression #lambda | '(' query ')' #subqueryExpression // This is an extension to ANSI SQL, which considers EXISTS to be a | EXISTS '(' query ')' #exists | CASE valueExpression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CAST '(' expression AS dataType ')' #cast | TRY_CAST '(' expression AS dataType ')' #cast | ARRAY '[' (expression (',' expression)*)? ']' #arrayConstructor | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier[null] #columnReference | expr=primaryExpression '.' fieldName=identifier[null] #dereference | name=CURRENT_DATE #specialDateTimeFunction | name=CURRENT_TIME ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction | name=CURRENT_TIMESTAMP ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction | name=LOCALTIME ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction | name=LOCALTIMESTAMP ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction | name=CURRENT_USER #currentUser | SUBSTRING '(' valueExpression FROM valueExpression (FOR valueExpression)? ')' #substring | NORMALIZE '(' valueExpression (',' normalForm)? ')' #normalize | EXTRACT '(' identifier[null] FROM valueExpression ')' #extract | '(' expression ')' #parenthesizedExpression | GROUPING '(' (qualifiedName (',' qualifiedName)*)? ')' #groupingOperation ; timeZoneSpecifier : TIME ZONE interval #timeZoneInterval | TIME ZONE string #timeZoneString ; interval : INTERVAL sign=(PLUS | MINUS)? string from=intervalField (TO to=intervalField)? ; orderBy : ORDER BY sortItem (',' sortItem)* ; string : STRING #basicStringLiteral | UNICODE_STRING (UESCAPE STRING)? #unicodeStringLiteral ; number : DECIMAL_VALUE #decimalLiteral | DOUBLE_VALUE #doubleLiteral | INTEGER_VALUE #integerLiteral ; nullTreatment : IGNORE NULLS | RESPECT NULLS ; comparisonOperator : EQ | NEQ | LT | LTE | GT | GTE ; comparisonQuantifier : ALL | SOME | ANY ; booleanValue : TRUE | FALSE ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; normalForm : NFD | NFC | NFKD | NFKC ; //dataTypes // : '(' (dataType (',' dataType)*)? ')' // ; dataType : primitiveType | arrayType | mapType | structType | unionType ; primitiveType : TINYINT | SMALLINT | INT | BIGINT | BOOLEAN | FLOAT | DOUBLE | DOUBLE PRECISION | STRING | BINARY | TIMESTAMP | DECIMAL | DECIMAL '(' INTEGER_VALUE ',' INTEGER_VALUE ')' | DATE | VARCHAR | CHAR ; arrayType : ARRAY '<' dataType '>' ; mapType : MAP < primitiveType, dataType > ; structType : STRUCT '<' columnName=identifier[null] ':' dataType (COMMENT comment=string)? (',' columnName=identifier[null] ':' dataType (COMMENT comment=string)? )* '>' ; unionType : UNIONTYPE '<' dataType (',' dataType)* '>' ; parameterExpression returns [int index] : '?' { $index = NextBindParameterIndex(); } ; //type // : type ARRAY // | ARRAY '<' type '>' // | MAP '<' type ',' type '>' // | ROW '(' identifier[null] type (',' identifier[null] type)* ')' // | baseType ('(' typeParameter (',' typeParameter)* ')')? // | INTERVAL from=intervalField TO to=intervalField // ; //typeParameter // : INTEGER_VALUE | type // ; // //baseType // : TIME_WITH_TIME_ZONE // | TIMESTAMP_WITH_TIME_ZONE // | DOUBLE_PRECISION // | qualifiedName // ; whenClause : WHEN condition=expression THEN result=expression ; filter : FILTER '(' WHERE booleanExpression ')' ; over : OVER '(' windowSpecification ')' ; windowSpecification: partitionBy? orderBy? windowFrame? ; partitionBy: PARTITION BY partition+=expression (',' partition+=expression)* ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=PRECEDING #unboundedFrame | UNBOUNDED boundType=FOLLOWING #unboundedFrame | CURRENT ROW #currentRowBound | expression boundType=(PRECEDING | FOLLOWING) #boundedFrame // expression should be unsignedLiteral ; explainOption : FORMAT value=(TEXT | GRAPHVIZ | JSON) #explainFormat | TYPE value=(LOGICAL | DISTRIBUTED | VALIDATE | IO) #explainType ; //transactionMode // : ISOLATION LEVEL levelOfIsolation #isolationLevel // | READ accessMode=(ONLY | WRITE) #transactionAccessMode // ; //levelOfIsolation // : READ UNCOMMITTED #readUncommitted // | READ COMMITTED #readCommitted // | REPEATABLE READ #repeatableRead // | SERIALIZABLE #serializable // ; //callArgument // : expression #positionalArgument // | identifier[null] '=>' expression #namedArgument // ; //privilege // : SELECT | DELETE | INSERT | identifier[null] // ; qualifiedName returns [QsiQualifiedIdentifier qqi] locals [List buffer] @init { $buffer = new List(); } @after { $qqi = new QsiQualifiedIdentifier($buffer); } : identifier[$buffer] ('.' identifier[$buffer] )* ; //grantor // : CURRENT_USER #currentUserGrantor // | CURRENT_ROLE #currentRoleGrantor // | principal #specifiedPrincipal // ; //principal // : USER identifier[null] #userPrincipal // | ROLE identifier[null] #rolePrincipal // | identifier[null] #unspecifiedPrincipal // ; //roles // : identifier[null] (',' identifier[null])* // ; identifier[List buffer] returns [QsiIdentifier qi] @after { $buffer?.Add($qi); } : i=IDENTIFIER { $qi = new QsiIdentifier($i.text, false); } #unquotedIdentifier | i=QUOTED_IDENTIFIER { $qi = new QsiIdentifier($i.text, true); } #quotedIdentifier | ki=nonReserved { $qi = new QsiIdentifier($ki.text, false); } #unquotedIdentifier | i=BACKQUOTED_IDENTIFIER { $qi = new QsiIdentifier($i.text, true); } #backQuotedIdentifier | i=DIGIT_IDENTIFIER { $qi = new QsiIdentifier($i.text, false); } #digitIdentifier ; nonReserved // IMPORTANT: this rule must only contain tokens. Nested rules are not supported. See SqlParser.exitNonReserved : ADD | AFTER | ADMIN | ALL | ANALYZE | ANY | ARRAY | ASC | AT | BERNOULLI | CALL | CALLED | CASCADE | CATALOGS | CHANGE | COLUMN | COLUMNS | COMMENT | COMMIT | COMMITTED | CURRENT | CURRENT_ROLE | DATA | DATE | DAY | DEFINER | DESC | DETERMINISTIC | DISTRIBUTED | EXCLUDING | EXPLAIN | EXTERNAL | FILTER | FIRST | FOLLOWING | FORMAT | FUNCTION | FUNCTIONS | GRANT | GRANTED | GRANTS | GRAPHVIZ | HOUR | IF | IGNORE | INCLUDING | INPUT | INTERVAL | INVOKER | IO | ISOLATION | JSON | LANGUAGE | LAST | LATERAL | LEVEL | LIMIT | LOGICAL | MAP | MATERIALIZED | MINUTE | MONTH | NAME | NFC | NFD | NFKC | NFKD | NO | NONE | NULLIF | NULLS | OFFSET | ONLY | OPTION | ORDINALITY | OUTPUT | OVER | PARTITION | PARTITIONS | POSITION | PRECEDING | PRIVILEGES | PROPERTIES | RANGE | READ | REFRESH | RENAME | REPEATABLE | REPLACE | RESET | RESPECT | RESTRICT | RETURN | RETURNS | REVOKE | ROLE | ROLES | ROLLBACK | ROW | ROWS | SCHEMA | SCHEMAS | SECOND | SECURITY | SERIALIZABLE | SESSION | SET | SETS | SQL | SHOW | SOME | START | STATS | SUBSTRING | SYSTEM | TABLES | TABLESAMPLE | TEMPORARY | TEXT | TIME | TIMESTAMP | TO | TRANSACTION | TRY_CAST | TYPE | UNBOUNDED | UNCOMMITTED | USE | USER | VALIDATE | VERBOSE | VIEW | WORK | WRITE | YEAR | ZONE | SYNC | PROTECTION | PURGE | SKEWED | DIRECTORIES | SORTED | REMOTE | MANAGEDLOCATION; ADD: 'ADD'; ADMIN: 'ADMIN'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANY: 'ANY'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; BERNOULLI: 'BERNOULLI'; BETWEEN: 'BETWEEN'; BY: 'BY'; CALL: 'CALL'; CALLED: 'CALLED'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CATALOGS: 'CATALOGS'; CHANGE: 'CHANGE'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMMITTED: 'COMMITTED'; CONSTRAINT: 'CONSTRAINT'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_ROLE: 'CURRENT_ROLE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATE: 'DATE'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEALLOCATE: 'DEALLOCATE'; DEFINER: 'DEFINER'; DELETE: 'DELETE'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DETERMINISTIC: 'DETERMINISTIC'; DISTINCT: 'DISTINCT'; DISTRIBUTED: 'DISTRIBUTED'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; EXCEPT: 'EXCEPT'; EXCLUDING: 'EXCLUDING'; EXECUTE: 'EXECUTE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXTRACT: 'EXTRACT'; EXTERNAL: 'EXTERNAL'; FALSE: 'FALSE'; FILTER: 'FILTER'; FIRST: 'FIRST'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FORMAT: 'FORMAT'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GRANT: 'GRANT'; GRANTED: 'GRANTED'; GRANTS: 'GRANTS'; GRAPHVIZ: 'GRAPHVIZ'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IN: 'IN'; INCLUDING: 'INCLUDING'; INNER: 'INNER'; INPUT: 'INPUT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; INVOKER: 'INVOKER'; IO: 'IO'; IS: 'IS'; ISOLATION: 'ISOLATION'; JSON: 'JSON'; JOIN: 'JOIN'; LANGUAGE: 'LANGUAGE'; LAST: 'LAST'; LATERAL: 'LATERAL'; LEFT: 'LEFT'; LEVEL: 'LEVEL'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LOCATION: 'LOCATION'; LOCALTIME: 'LOCALTIME'; LOCALTIMESTAMP: 'LOCALTIMESTAMP'; LOGICAL: 'LOGICAL'; MAP: 'MAP'; MATERIALIZED: 'MATERIALIZED'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; NAME: 'NAME'; NATURAL: 'NATURAL'; NFC : 'NFC'; NFD : 'NFD'; NFKC : 'NFKC'; NFKD : 'NFKD'; NO: 'NO'; NONE: 'NONE'; NORMALIZE: 'NORMALIZE'; NOT: 'NOT'; NULL: 'NULL'; NULLIF: 'NULLIF'; NULLS: 'NULLS'; OFFSET: 'OFFSET'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OR: 'OR'; ORDER: 'ORDER'; ORDINALITY: 'ORDINALITY'; OUTER: 'OUTER'; OUTPUT: 'OUTPUT'; OVER: 'OVER'; PARTITION: 'PARTITION'; PARTITIONS: 'PARTITIONS'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PREPARE: 'PREPARE'; PRIVILEGES: 'PRIVILEGES'; PROPERTIES: 'PROPERTIES'; RANGE: 'RANGE'; READ: 'READ'; RECURSIVE: 'RECURSIVE'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPEATABLE: 'REPEATABLE'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; RETURN: 'RETURN'; RETURNS: 'RETURNS'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SCHEMAS: 'SCHEMAS'; SECOND: 'SECOND'; SECURITY: 'SECURITY'; SELECT: 'SELECT'; SERIALIZABLE: 'SERIALIZABLE'; SESSION: 'SESSION'; SET: 'SET'; SETS: 'SETS'; SHOW: 'SHOW'; SOME: 'SOME'; SQL: 'SQL'; START: 'START'; STATS: 'STATS'; SUBSTRING: 'SUBSTRING'; SYSTEM: 'SYSTEM'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TEMPORARY: 'TEMPORARY'; TEXT: 'TEXT'; THEN: 'THEN'; TIME: 'TIME'; TIMESTAMP: 'TIMESTAMP'; TO: 'TO'; TRANSACTION: 'TRANSACTION'; TRUE: 'TRUE'; TRY_CAST: 'TRY_CAST'; TYPE: 'TYPE'; UESCAPE: 'UESCAPE'; UNBOUNDED: 'UNBOUNDED'; UNCOMMITTED: 'UNCOMMITTED'; UNION: 'UNION'; UNNEST: 'UNNEST'; UNLOAD: 'UNLOAD'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALIDATE: 'VALIDATE'; VALUES: 'VALUES'; VERBOSE: 'VERBOSE'; VIEW: 'VIEW'; WHEN: 'WHEN'; WHERE: 'WHERE'; WITH: 'WITH'; WORK: 'WORK'; WRITE: 'WRITE'; YEAR: 'YEAR'; ZONE: 'ZONE'; PARTITIONED: 'PARTITIONED'; CLUSTERED: 'CLUSTERED'; BUCKETS: 'BUCKETS'; STORED: 'STORED'; SERDEPROPERTIES: 'SERDEPROPERTIES'; TBLPROPERTIES: 'TBLPROPERTIES'; DELIMITED: 'DELIMITED'; FIELDS: 'FIELDS'; TERMINATED: 'TERMINATED'; ESCAPED: 'ESCAPED'; COLLECTION: 'COLLECTION'; ITEMS: 'ITEMS'; KEYS: 'KEYS'; LINES: 'LINES'; DEFINED: 'DEFINED'; SERDE: 'SERDE'; SEQUENCEFILE: 'SEQUENCEFILE'; TEXTFILE: 'TEXTFILE'; RCFILE: 'RCFILE'; ORC: 'ORC'; PARQUET: 'PARQUET'; AVRO: 'AVRO'; INPUTFORMAT: 'INPUTFORMAT'; OUTPUTFORMAT: 'OUTPUTFORMAT'; EXTENDED: 'EXTENDED'; FORMATTED: 'FORMATTED'; MSCK: 'MSCK'; REPAIR: 'REPAIR'; DATABASES: 'DATABASES'; VIEWS: 'VIEWS'; SYNC: 'SYNC'; PROTECTION: 'PROTECTION'; PURGE: 'PURGE'; SKEWED: 'SKEWED'; DIRECTORIES: 'DIRECTORIES'; SORTED: 'SORTED'; JSONFILE: 'JSONFILE'; REMOTE: 'REMOTE'; MANAGEDLOCATION: 'MANAGEDLOCATION'; TINYINT: 'TINYINT'; BIGINT: 'BIGINT'; INT: 'INT'; SMALLINT: 'SMALLINT'; BOOLEAN: 'BOOLEAN'; FLOAT: 'FLOAT'; DOUBLE: 'DOUBLE'; PRECISION: 'PRECISION'; BINARY: 'BINARY'; DECIMAL: 'DECIMAL'; VARCHAR: 'VARCHAR'; CHAR: 'CHAR'; STRUCT: 'STRUCT'; UNIONTYPE: 'UNIONTYPE'; EQ : '='; NEQ : '<>' | '!='; LT : '<'; LTE : '<='; GT : '>'; GTE : '>='; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; CONCAT: '||'; STRING : '\\'' ( ~'\\'' | '\\'\\'' )* '\\'' ; UNICODE_STRING : 'U&\\'' ( ~'\\'' | '\\'\\'' )* '\\'' ; // Note: we allow any character inside the binary literal and validate // its a correct literal when the AST is being constructed. This // allows us to provide more meaningful error messages to the user BINARY_LITERAL : 'X\\'' (~'\\'')* '\\'' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; DOUBLE_VALUE : DIGIT+ ('.' DIGIT*)? EXPONENT | '.' DIGIT+ EXPONENT ; IDENTIFIER : (LETTER | '_') (LETTER | DIGIT | '_' | '@' | ':')* ; DIGIT_IDENTIFIER : DIGIT (LETTER | DIGIT | '_' | '@' | ':')+ ; QUOTED_IDENTIFIER : '""' ( ~'""' | '""""' )* '""' ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; TIME_WITH_TIME_ZONE : 'TIME' WS 'WITH' WS 'TIME' WS 'ZONE' ; TIMESTAMP_WITH_TIME_ZONE : 'TIMESTAMP' WS 'WITH' WS 'TIME' WS 'ZONE' ; DOUBLE_PRECISION : 'DOUBLE' WS 'PRECISION' ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",16312,True,2844.1527962687915,median "/* * Copyright (C) 2015 Ulrich Wolffgang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ /* * Cobol 85 Grammar for ANTLR4 * * This is an approximate grammar for Cobol 85. It is akin but neither * copied from nor identical to Cobol.jj, Cobol.kg and VS COBOL II grammars. * Tested against the NIST test suite. * * Characteristics: * * 1. Passes the NIST tests. * * 2. To be used in conjunction with the provided preprocessor, which executes * COPY and REPLACE statements. * * * Known limitations (work under progress): * * 1. Picture strings are parsed as (groups of) terminal symbols. * * 2. Comments are skipped. * * * Change log: * * v1.0 * - fixes * - compiler options * * v0.9 Initial revision */ grammar Cobol85; options { language = Java; } startRule : compilationUnit EOF; compilationUnit : programUnit+ ; programUnit : compilerOptions? identificationDivision environmentDivision? dataDivision? procedureDivision? programUnit* endProgramStatement? ; endProgramStatement : END PROGRAM programName DOT ; // --- compiler options -------------------------------------------------------------------- compilerOptions : (PROCESS compilerOption+)+ ; compilerOption : APOST | ARITH LPARENCHAR EXTEND RPARENCHAR | CODEPAGE LPARENCHAR literal RPARENCHAR | DBCS | LIB | NOSEQ | NOSTDTRUNC | OPTIMIZE LPARENCHAR FULL RPARENCHAR | XOPTS LPARENCHAR compilerSubOption+ RPARENCHAR ; compilerSubOption : SP | APOST ; // --- identification division -------------------------------------------------------------------- identificationDivision : (IDENTIFICATION | ID) DIVISION DOT programIdParagraph identificationDivisionBody* ; identificationDivisionBody : authorParagraph | installationParagraph | dateWrittenParagraph | dateCompiledParagraph | securityParagraph ; // - program id paragraph ---------------------------------- programIdParagraph : PROGRAM_ID DOT programName (IS? (COMMON | INITIAL | LIBRARY | DEFINITION) PROGRAM?)? DOT ; // - author paragraph ---------------------------------- authorParagraph : AUTHOR DOT commentEntry? ; // - installation paragraph ---------------------------------- installationParagraph : INSTALLATION DOT commentEntry? ; // - date written paragraph ---------------------------------- dateWrittenParagraph : DATE_WRITTEN DOT commentEntry? ; // - date compiled paragraph ---------------------------------- dateCompiledParagraph : DATE_COMPILED DOT commentEntry? ; // - security paragraph ---------------------------------- securityParagraph : SECURITY DOT commentEntry? ; // --- environment division -------------------------------------------------------------------- environmentDivision : ENVIRONMENT DIVISION DOT environmentDivisionBody* ; environmentDivisionBody : configurationSection | specialNamesParagraph | inputOutputSection ; // -- configuration section ---------------------------------- configurationSection : CONFIGURATION SECTION DOT configurationSectionParagraph* ; // - configuration section paragraph ---------------------------------- configurationSectionParagraph : sourceComputerParagraph | objectComputerParagraph ; // - source computer paragraph ---------------------------------- sourceComputerParagraph : SOURCE_COMPUTER DOT computerName (WITH? DEBUGGING MODE)? DOT ; // - object computer paragraph ---------------------------------- objectComputerParagraph : OBJECT_COMPUTER DOT computerName objectComputerClause* DOT ; objectComputerClause : memorySizeClause | diskSizeClause | collatingSequenceClause | segmentLimitClause | characterSetClause ; memorySizeClause : MEMORY SIZE? integerLiteral (WORDS | CHARACTERS | MODULES)? ; diskSizeClause : DISK SIZE? IS? integerLiteral (WORDS | MODULES)? ; collatingSequenceClause : PROGRAM? COLLATING? SEQUENCE IS? alphabetName+ ; segmentLimitClause : SEGMENT_LIMIT IS? integerLiteral ; characterSetClause : CHARACTER SET commentEntry? ; // - special names paragraph ---------------------------------- specialNamesParagraph : SPECIAL_NAMES DOT (specialNameClause+ DOT)? ; specialNameClause : channelClause | odtClause | alphabetClause | classClause | currencySignClause | decimalPointClause | symbolicCharactersClause | environmentSwitchNameClause ; channelClause : CHANNEL integerLiteral IS? mnemonicName ; odtClause : ODT IS? mnemonicName ; alphabetClause : ALPHABET alphabetName (FOR ALPHANUMERIC)? IS? ( EBCDIC | ASCII | STANDARD_1 | STANDARD_2 | NATIVE | cobolWord | (literal ( ( (THROUGH | THRU) literal | (ALSO literal)+ ) )? )+ ) ; classClause : CLASS className (FOR? (ALPHANUMERIC | NATIONAL))? IS? ( (identifier | literal) ((THROUGH | THRU) (identifier | literal))? )+ ; currencySignClause : CURRENCY SIGN? IS? literal ; decimalPointClause : DECIMAL_POINT IS? COMMA ; symbolicCharactersClause : SYMBOLIC CHARACTERS? (FOR? (ALPHANUMERIC | NATIONAL))? (symbolicCharacter+ (IS | ARE)? integerLiteral+)+ (IN alphabetName)? ; environmentSwitchNameClause : environmentName IS? mnemonicName specialNamesStatusPhrase? | specialNamesStatusPhrase ; specialNamesStatusPhrase : ON STATUS? IS? condition (OFF STATUS? IS? condition)? | OFF STATUS? IS? condition (ON STATUS? IS? condition)? ; // -- input output section ---------------------------------- inputOutputSection : INPUT_OUTPUT SECTION DOT inputOutputSectionParagraph* ; // - input output section paragraph ---------------------------------- inputOutputSectionParagraph : fileControlParagraph | ioControlParagraph ; // - file control paragraph ---------------------------------- fileControlParagraph : FILE_CONTROL (DOT? fileControlEntry)+ DOT ; fileControlEntry : selectClause fileControlClause* ; fileControlClause : assignClause | reserveClause | organizationClause | paddingCharacterClause | recordDelimiterClause | accessModeClause | recordKeyClause | alternateRecordKeyClause | fileStatusClause | passwordClause | relativeKeyClause ; assignClause : ASSIGN TO? (assignmentName | literal) ; selectClause : SELECT OPTIONAL? fileName ; reserveClause : RESERVE (integerLiteral | NO) ALTERNATE? (AREA | AREAS)? ; organizationClause : (ORGANIZATION IS?)? (LINE | RECORD BINARY | RECORD | BINARY)? (SEQUENTIAL | RELATIVE | INDEXED) ; paddingCharacterClause : PADDING CHARACTER? IS? (qualifiedDataName | literal) ; recordDelimiterClause : RECORD DELIMITER IS? (STANDARD_1 | IMPLICIT | assignmentName) ; accessModeClause : ACCESS MODE? IS? ( SEQUENTIAL | RANDOM | DYNAMIC | EXCLUSIVE ) ; recordKeyClause : RECORD KEY? IS? qualifiedDataName passwordClause? (WITH? DUPLICATES)? ; alternateRecordKeyClause : ALTERNATE RECORD KEY? IS? qualifiedDataName passwordClause? (WITH? DUPLICATES)? ; passwordClause : PASSWORD IS? dataName ; fileStatusClause : FILE? STATUS IS? qualifiedDataName qualifiedDataName? ; relativeKeyClause : RELATIVE KEY? IS? qualifiedDataName ; // - io control paragraph ---------------------------------- ioControlParagraph : I_O_CONTROL DOT (ioControlClause (DOT? ioControlClause)* DOT)? ; ioControlClause : obsoletePictureStringClause | rerunClause | sameAreaClause | multipleFileClause | commitmentControlClause ; rerunClause : RERUN ( ON (assignmentName | fileName) )? EVERY (rerunEveryRecords | rerunEveryOf | rerunEveryClock) ; rerunEveryRecords : integerLiteral RECORDS ; rerunEveryOf : END? OF? (REEL | UNIT) OF fileName ; rerunEveryClock : integerLiteral CLOCK_UNITS? ; sameAreaClause : SAME (RECORD | SORT | SORT_MERGE)? AREA? FOR? fileName+ ; multipleFileClause : MULTIPLE FILE TAPE? CONTAINS? (fileName POSITION? integerLiteral?)+ ; commitmentControlClause : COMMITMENT CONTROL FOR? fileName ; // --- data division -------------------------------------------------------------------- dataDivision : DATA DIVISION DOT dataDivisionBody* ; dataDivisionBody : fileSection | workingStorageSection | linkageSection | communicationSection | screenSection | reportSection ; // -- file section ---------------------------------- fileSection : FILE SECTION DOT (fileAndSortDescriptionEntry dataDescriptionEntry*)* ; fileAndSortDescriptionEntry : (FD | SD) fileName (DOT? fileAndSortDescriptionEntryClause)* DOT ; fileAndSortDescriptionEntryClause : externalClause | globalClause | blockContainsClause | recordContainsClause | labelRecordsClause | valueOfClause | dataRecordClause | linageClause | codeSetClause | reportClause | recordingModeClause ; externalClause : IS? EXTERNAL ; globalClause : IS? GLOBAL ; blockContainsClause : BLOCK CONTAINS? (integerLiteral TO)? integerLiteral (RECORDS | CHARACTERS)? ; recordContainsClause : RECORD CONTAINS? ( (integerLiteral TO)? integerLiteral CHARACTERS? | IS? VARYING IN? SIZE? (FROM? integerLiteral (TO integerLiteral)? CHARACTERS?)? (DEPENDING ON? qualifiedDataName)? ) ; labelRecordsClause : LABEL (RECORD IS? | RECORDS ARE?) (OMITTED | STANDARD | dataName+) ; valueOfClause : VALUE OF (systemName IS? (qualifiedDataName | literal))+ ; dataRecordClause : DATA (RECORD IS? | RECORDS ARE?) dataName+ ; linageClause : LINAGE IS? (dataName | integerLiteral) LINES? ( WITH? FOOTING AT? (dataName | integerLiteral) | LINES? AT? TOP (dataName | integerLiteral) | LINES? AT? BOTTOM (dataName | integerLiteral) )* ; recordingModeClause : RECORDING MODE? IS? modeStatement ; modeStatement : cobolWord ; codeSetClause : CODE_SET IS? alphabetName ; reportClause : (REPORT IS? | REPORTS ARE?) reportName+ ; dataDescriptionEntry : INTEGERLITERAL (dataName | FILLER)? dataDescriptionEntryClause* DOT | LEVEL_NUMBER_66 dataName renamesClause DOT | LEVEL_NUMBER_77 dataDescName dataDescriptionEntryClause* DOT | LEVEL_NUMBER_88 conditionName conditionValueClause DOT ; dataDescriptionEntryClause : dataPictureClause | dataValueClause | dataUsageClause | dataRedefinesClause | dataExternalClause | dataGlobalClause | dataSignClause | dataOccursClause | dataSynchronizedClause | dataJustifiedClause | dataBlankWhenZeroClause | obsoletePictureStringClause ; dataRedefinesClause : REDEFINES dataName ; dataBlankWhenZeroClause : BLANK WHEN? (ZERO | ZEROS | ZEROES) ; dataJustifiedClause : (JUSTIFIED | JUST) RIGHT? ; dataOccursClause : OCCURS (integerLiteral TO)? integerLiteral TIMES? (DEPENDING ON? qualifiedDataName)? ( (ASCENDING | DESCENDING) KEY? IS? qualifiedDataName+ )* (INDEXED BY? indexName+)? ; dataPictureClause : (PICTURE | PIC) IS? pictureString ; pictureString : (pictureChars+ pictureCardinality?)+ ; pictureChars : DOLLARCHAR | IDENTIFIER | integerLiteral | NUMERICLITERAL | keyword | picturePunctuation | ASTERISKCHAR | DOUBLEASTERISKCHAR | LPARENCHAR | RPARENCHAR | PLUSCHAR | MINUSCHAR | LESSTHANCHAR | MORETHANCHAR ; pictureCardinality : LPARENCHAR integerLiteral RPARENCHAR ; picturePunctuation : SLASHCHAR | COMMACHAR | DOT | COLONCHAR ; dataExternalClause : IS? EXTERNAL ; dataGlobalClause : IS? GLOBAL ; dataUsageClause : (USAGE IS?)? ( BINARY | COMP | COMP_1 | COMP_2 | COMP_3 | COMP_4 | COMPUTATIONAL | COMPUTATIONAL_1 | COMPUTATIONAL_2 | COMPUTATIONAL_3 | COMPUTATIONAL_4 | DISPLAY | DISPLAY_1 | INDEX | PACKED_DECIMAL | POINTER ) ; dataSignClause : (SIGN IS?)? (LEADING | TRAILING) (SEPARATE CHARACTER?)? ; dataSynchronizedClause : (SYNCHRONIZED | SYNC) (LEFT | RIGHT)? ; dataValueClause : (VALUE IS? | VALUES ARE?) ( (literal | cobolWord) ( (THROUGH | THRU) literal )? )+ ; conditionValueClause : dataValueClause ; renamesClause : RENAMES qualifiedDataName ( (THROUGH | THRU) qualifiedDataName )? ; // -- working storage section ---------------------------------- workingStorageSection : WORKING_STORAGE SECTION DOT dataDescriptionEntry* ; // -- linkage section ---------------------------------- linkageSection : LINKAGE SECTION DOT dataDescriptionEntry* ; // -- communication section ---------------------------------- communicationSection : COMMUNICATION SECTION DOT (communicationDescriptionEntry | dataDescriptionEntry)* ; communicationDescriptionEntry : communicationDescriptionEntryFormat1 | communicationDescriptionEntryFormat2 | communicationDescriptionEntryFormat3 ; communicationDescriptionEntryFormat1 : CD cdName FOR INITIAL? INPUT ( ( SYMBOLIC QUEUE IS dataDescName | SYMBOLIC SUB_QUEUE_1 IS dataDescName | SYMBOLIC SUB_QUEUE_2 IS dataDescName | SYMBOLIC SUB_QUEUE_3 IS dataDescName | MESSAGE DATE IS dataDescName | MESSAGE TIME IS dataDescName | SYMBOLIC SOURCE IS dataDescName | TEXT LENGTH IS dataDescName | END KEY IS dataDescName | STATUS KEY IS dataDescName | MESSAGE COUNT IS dataDescName ) | dataDescName )* DOT ; communicationDescriptionEntryFormat2 : CD cdName FOR OUTPUT ( DESTINATION COUNT IS dataDescName | TEXT LENGTH IS dataDescName | STATUS KEY IS dataDescName | DESTINATION TABLE OCCURS integerLiteral TIMES (INDEXED BY indexName+)? | ERROR KEY IS dataDescName | SYMBOLIC DESTINATION IS dataDescName ) DOT ; communicationDescriptionEntryFormat3 : CD cdName FOR INITIAL I_O ( ( MESSAGE DATE IS dataDescName | MESSAGE TIME IS dataDescName | SYMBOLIC TERMINAL IS dataDescName | TEXT LENGTH IS dataDescName | END KEY IS dataDescName | STATUS KEY IS dataDescName ) | dataDescName+ ) DOT ; // -- screen section ---------------------------------- screenSection : SCREEN SECTION DOT ; // -- report section ---------------------------------- reportSection : REPORT SECTION DOT ( reportDescriptionEntry reportGroupDescriptionEntry+ )* ; reportDescriptionEntry : RD reportName DOT ; reportGroupDescriptionEntry : reportGroupDescriptionEntryFormat1 | reportGroupDescriptionEntryFormat2 | reportGroupDescriptionEntryFormat3 ; reportGroupDescriptionEntryFormat1 : integerLiteral dataName ( LINE NUMBER? IS? ( integerLiteral (ON? NEXT PAGE)? | PLUS integerLiteral | NEXT PAGE ) )? ( NEXT GROUP IS? ( integerLiteral | PLUS integerLiteral | NEXT PAGE ) )? TYPE IS? ( (REPORT HEADING | RH) | (PAGE HEADING | PH) | (CONTROL HEADING | CH) (dataName | FINAL) | (DETAIL | DE) | (CONTROL FOOTING | CF) (dataName | FINAL) | (PAGE FOOTING | PF) | (REPORT FOOTING | RF) ) ( USAGE IS? (DISPLAY | DISPLAY_1) )? DOT ; reportGroupDescriptionEntryFormat2 : integerLiteral dataName? ( LINE NUMBER? IS? ( integerLiteral (ON? NEXT PAGE)? | PLUS integerLiteral | NEXT PAGE ) )? ( USAGE IS? (DISPLAY | DISPLAY_1) ) DOT ; reportGroupDescriptionEntryFormat3 : integerLiteral dataName? ( dataPictureClause ( (USAGE IS? (DISPLAY | DISPLAY_1)) | (SIGN IS? (LEADING | TRAILING) SEPARATE CHARACTER?) | ((JUSTIFIED | JUST) RIGHT?) | (BLANK WHEN? ZERO) | ( LINE? NUMBER? IS? ( integerLiteral (ON? NEXT PAGE)? | PLUS integerLiteral ) ) | (COLUMN NUMBER? IS? integerLiteral) | ( SOURCE IS? identifier | VALUE IS? literal | ( SUM identifier (COMMACHAR identifier)+ (UPON dataName (COMMACHAR dataName)+)? ) | (RESET ON? (FINAL | dataName)) ) | (GROUP INDICATE?) )* ) DOT ; // --- procedure division -------------------------------------------------------------------- procedureDivision : PROCEDURE DIVISION (USING dataName+)? (GIVING dataName)? DOT procedureDeclaratives? procedureDivisionBody ; procedureDeclaratives : DECLARATIVES DOT ( procedureSectionHeader DOT useStatement DOT paragraphs )+ END DECLARATIVES DOT ; procedureDivisionBody : paragraphs procedureSection* ; procedureSectionHeader : sectionName SECTION integerLiteral? ; // -- procedure section ---------------------------------- procedureSection : procedureSectionHeader DOT paragraphs ; paragraphs : sentence* paragraph* ; paragraph : paragraphName DOT ( exitStatement | alteredGoTo | sentence* ) ; sentence : statements DOT ; statements : statement* ; statement : acceptStatement | addStatement | alterStatement | callStatement | cancelStatement | closeStatement | computeStatement | continueStatement | deleteStatement | disableStatement | displayStatement | divideStatement | enableStatement | entryStatement | evaluateStatement | exitProgramStatement | exitStatement | generateStatement | gobackStatement | goToStatement | ifStatement | initializeStatement | initiateStatement | inspectStatement | mergeStatement | moveStatement | multiplyStatement | openStatement | performStatement | purgeStatement | readStatement | receiveStatement | releaseStatement | returnStatement | rewriteStatement | searchStatement | sendStatement | setStatement | sortStatement | startStatement | stopStatement | stringStatement | subtractStatement | terminateStatement | unstringStatement | writeStatement ; // accept statement acceptStatement : acceptFromDate | acceptFromMnemonic | acceptMessageCount ; acceptFromDate : ACCEPT identifier FROM ( DATE YYYYMMDD? | DAY YYYYDDD? | DAY_OF_WEEK | TIME | TIMER | YEAR | YYYYMMDD | YYYYDDD ) ; acceptFromMnemonic : ACCEPT identifier (FROM mnemonicName)? ; acceptMessageCount : ACCEPT identifier MESSAGE? COUNT ; // add statement addStatement : ADD ( addToStatement | addToGivingStatement | addCorrespondingStatement ) (ON? SIZE ERROR statements)? (NOT ON? SIZE ERROR statements)? END_ADD? ; addToStatement : (identifier | literal)+ TO (identifier ROUNDED?)+ ; addToGivingStatement : (identifier | literal)+ (TO (identifier)+)? GIVING (identifier ROUNDED?)+ ; addCorrespondingStatement : (CORRESPONDING | CORR) identifier TO identifier ROUNDED? ; // altered go to statement alteredGoTo : GO TO? DOT ; // alter statement alterStatement : ALTER (procedureName TO (PROCEED TO)? procedureName)+ ; // call statement callStatement : CALL (identifier | literal) ( USING (callByReferenceStatement | callByContentStatement)+ )? (ON? OVERFLOW statements)? onExceptionClause? notOnExceptionClause? END_CALL? ; callByReferenceStatement : (BY? REFERENCE)? (identifier | ADDRESS OF identifier | fileName)+ ; callByContentStatement : BY? CONTENT ((LENGTH OF)? identifier | ADDRESS OF identifier | literal)+ ; // cancel statement cancelStatement : CANCEL (identifier | literal)+ ; // close statement closeStatement : CLOSE ( fileName (closeReelUnitStatement | closeWithStatement)? )+ ; closeReelUnitStatement : (REEL | UNIT) (FOR? REMOVAL | WITH? NO REWIND)? ; closeWithStatement : WITH? (NO REWIND | LOCK) ; // compute statement computeStatement : COMPUTE (identifier ROUNDED?)+ (EQUALCHAR | EQUAL) arithmeticExpression (ON? SIZE ERROR statements)? (NOT ON? SIZE ERROR statements)? END_COMPUTE? ; // continue statement continueStatement : CONTINUE ; // delete statement deleteStatement : DELETE fileName RECORD? (INVALID KEY? statements)? (NOT INVALID KEY? statements)? END_DELETE? ; // disable statement disableStatement : DISABLE (INPUT TERMINAL? | I_O TERMINAL | OUTPUT) cdName WITH KEY (identifier | literal) ; // display statement displayStatement : DISPLAY (identifier | literal)+ (UPON (mnemonicName | environmentName))? (WITH? NO ADVANCING)? ; // divide statement divideStatement : DIVIDE (identifier | literal) ( divideIntoStatement | divideIntoGivingStatement | divideIntoByGivingStatement ) (REMAINDER identifier)? (ON? SIZE ERROR statements)? (NOT ON? SIZE ERROR statements)? END_DIVIDE? ; divideIntoStatement : INTO (identifier | literal) (GIVING (identifier ROUNDED?)+)? ; divideIntoGivingStatement : INTO (identifier ROUNDED?)+ ; divideIntoByGivingStatement : BY (identifier | literal) (GIVING (identifier ROUNDED?)+)? ; // enable statement enableStatement : ENABLE (INPUT TERMINAL? | I_O TERMINAL | OUTPUT) cdName WITH? KEY (literal | identifier) ; // entry statement entryStatement : ENTRY literal (USING identifier+)? ; // evaluate statement evaluateStatement : EVALUATE evaluateValue (ALSO evaluateValue)* ( (WHEN evaluatePhrase (ALSO evaluatePhrase)*)+ statements )+ (WHEN OTHER statements)? END_EVALUATE? ; evaluateValue : arithmeticExpression | identifier | literal | condition ; evaluatePhrase : ANY | condition | booleanLiteral | NOT? (identifier | literal | arithmeticExpression) ( (THROUGH | THRU) (identifier | literal | arithmeticExpression) )? ; // exit program statement exitProgramStatement : EXIT PROGRAM ; // exit statement exitStatement : EXIT ; // generate statement generateStatement : GENERATE (dataName | reportName) ; // goback statement gobackStatement : GOBACK ; // goto statement goToStatement : GO TO? ( procedureName+ (DEPENDING ON? identifier)? | MORE_LABELS ) ; // if statement ifStatement : IF condition THEN? (statement* | NEXT SENTENCE) ( ELSE (statement* | NEXT SENTENCE) )? END_IF? ; // initialize statement initializeStatement : INITIALIZE identifier+ ( REPLACING ( ( ALPHABETIC | ALPHANUMERIC | NUMERIC | ALPHANUMERIC_EDITED | NUMERIC_EDITED | DBCS | EGCS ) DATA? BY (identifier | literal) )+ )? ; // initiate statement initiateStatement : INITIATE reportName+ ; // inspect statement inspectStatement : INSPECT identifier ( inspectTallyingPhrase | inspectConvertingPhrase | inspectReplacingPhrase ) ; inspectTallyingPhrase : TALLYING ( identifier FOR ( CHARACTERS inspectBeforeAfterPhrase* | (ALL | LEADING) ( (identifier | literal) inspectBeforeAfterPhrase* )+ )+ )+ inspectReplacingPhrase? ; inspectConvertingPhrase : CONVERTING (identifier | literal) TO (identifier | literal) inspectBeforeAfterPhrase* ; inspectReplacingPhrase : REPLACING ( CHARACTERS BY (identifier | literal) inspectBeforeAfterPhrase* | (ALL | LEADING | FIRST) ( (identifier | literal) BY (identifier | literal) inspectBeforeAfterPhrase* )+ )+ ; inspectBeforeAfterPhrase : (BEFORE | AFTER) INITIAL? (identifier | literal) ; // merge statement mergeStatement : MERGE fileName (ON? (ASCENDING | DESCENDING) KEY? qualifiedDataName+)+ (COLLATING? SEQUENCE IS? alphabetName)? USING fileName fileName+ ( OUTPUT PROCEDURE IS? procedureName ( (THROUGH | THRU) procedureName )? | GIVING fileName+ ) ; // move statement moveStatement : MOVE ( moveToStatement | moveCorrespondingToStatement ) ; moveToStatement : (identifier | literal) TO identifier+ ; moveCorrespondingToStatement : (CORRESPONDING | CORR) qualifiedDataName TO identifier+ ; // multiply statement multiplyStatement : ( multiplyRegular | multiplyGiving ) (ON? SIZE ERROR statements)? (NOT ON? SIZE ERROR statements)? END_MULTIPLY? ; multiplyRegular : MULTIPLY (identifier | literal) BY (identifier ROUNDED?)+ ; multiplyGiving : MULTIPLY (identifier | literal) BY (identifier | literal) GIVING (identifier ROUNDED?)+ ; // open statement openStatement : OPEN ( openInputStatement | openOutputStatement | openIOStatement | openExtendStatement )+ ; openInputStatement : INPUT (fileName (REVERSED | WITH? NO REWIND)?)+ ; openOutputStatement : OUTPUT (fileName (WITH? NO REWIND)?)+ ; openIOStatement : I_O fileName+ ; openExtendStatement : EXTEND fileName+ ; // perform statement performStatement : performInlineStatement | performProcedureStatement ; performInlineStatement : PERFORM performType? statement+ END_PERFORM ; performProcedureStatement : PERFORM procedureName ((THROUGH | THRU) procedureName)? performType? ; performType : performTimes | performUntil | performVarying ; performTimes : (identifier | integerLiteral) TIMES ; performUntil : performTestClause? UNTIL condition ; performVarying : performTestClause performVaryingClause | performVaryingClause performTestClause? ; performVaryingClause : VARYING (identifier | literal) FROM (identifier | literal | arithmeticExpression) BY (identifier | literal | arithmeticExpression) performUntil ( AFTER (identifier) FROM (identifier | literal | arithmeticExpression) BY (identifier | literal | arithmeticExpression) performUntil )* (statement+ END_PERFORM)? ; performTestClause : WITH? TEST (BEFORE | AFTER) ; // purge statement purgeStatement : PURGE cdName+ ; // read statement readStatement : READ fileName NEXT? RECORD? (INTO identifier)? ( WITH? ( (KEPT | NO) LOCK | WAIT ) )? (KEY IS? qualifiedDataName)? (INVALID KEY? statements)? (NOT INVALID KEY? statements)? (AT? END statements)? (NOT AT? END statements)? END_READ? ; // receive statement receiveStatement : RECEIVE ( dataName FROM (THREAD dataName | LAST THREAD | ANY THREAD) ( BEFORE TIME? (numericLiteral | identifier) | WITH? NO WAIT | THREAD IN? dataName | SIZE IN? (numericLiteral | identifier) | STATUS IN? (identifier) | onExceptionClause | notOnExceptionClause ) | cdName (MESSAGE | SEGMENT) INTO? identifier (NO DATA statements)? (WITH DATA statements)? ) END_RECEIVE? ; // release statement releaseStatement : RELEASE recordName (FROM qualifiedDataName)? ; // return statement returnStatement : RETURN fileName RECORD? (INTO qualifiedDataName)? AT? END statements (NOT AT? END statements)? END_RETURN? ; // rewrite statement rewriteStatement : REWRITE recordName (FROM identifier)? (INVALID KEY? statements)? (NOT INVALID KEY? statements)? END_REWRITE? ; // search statement searchStatement : SEARCH ALL? qualifiedDataName (VARYING qualifiedDataName)? (AT? END statements)? (WHEN condition (statements | NEXT SENTENCE))+ END_SEARCH? ; // send statement sendStatement : sendStatementSync | sendStatementAsync ; sendStatementSync : SEND (identifier | literal) (FROM identifier)? ( WITH (identifier | EGI | EMI | ESI) )? (REPLACING LINE?)? onExceptionClause? notOnExceptionClause? ; sendStatementAsync : SEND TO (TOP | BOTTOM) identifier onExceptionClause? notOnExceptionClause? ; // set statement setStatement : setToStatement | setUpDownByStatement ; setToStatement : SET ( identifier+ TO (identifier | ON | OFF | literal) )+ ; setUpDownByStatement : SET identifier+ (UP | DOWN) BY? (identifier | literal) ; // sort statement sortStatement : SORT fileName (ON? (ASCENDING | DESCENDING) KEY? qualifiedDataName+)+ (WITH? DUPLICATES IN? ORDER?)? (COLLATING? SEQUENCE IS? alphabetName)? (USING fileName+ | INPUT PROCEDURE IS? procedureName ((THROUGH | THRU) procedureName)?) (GIVING fileName+ | OUTPUT PROCEDURE IS? procedureName ((THROUGH | THRU) procedureName)?) ; // start statement startStatement : START fileName (KEY IS? ( EQUAL TO? | EQUALCHAR | GREATER THAN? | MORETHANCHAR | NOT LESS THAN? | NOT LESSTHANCHAR | GREATER THAN? OR EQUAL TO? | MORETHANOREQUAL ) qualifiedDataName)? (INVALID KEY? statements)? (NOT INVALID KEY? statements)? END_START? ; // stop statement stopStatement : STOP (RUN | literal) ; // string statement stringStatement : STRING ( (tableCall | literal)+ DELIMITED BY? (identifier | literal | SIZE) )+ INTO identifier (WITH? POINTER qualifiedDataName)? (ON? OVERFLOW statements)? (NOT ON? OVERFLOW statements)? END_STRING? ; // subtract statement subtractStatement : SUBTRACT ( subtractFromStatement | subtractFromGivingStatement | subtractCorrespondingStatement ) (ON? SIZE ERROR statements)? (NOT ON? SIZE ERROR statements)? END_SUBTRACT? ; subtractFromStatement : (identifier | literal)+ FROM (identifier ROUNDED?)+ ; subtractFromGivingStatement : (identifier | literal)+ FROM (identifier | literal) ROUNDED? GIVING (identifier ROUNDED?)+ ; subtractCorrespondingStatement : (CORRESPONDING | CORR) qualifiedDataName FROM qualifiedDataName ROUNDED? ; // terminate statement terminateStatement : TERMINATE reportName ; // unstring statement unstringStatement : UNSTRING qualifiedDataName ( DELIMITED BY? ALL? (identifier | literal) (OR ALL? (identifier | literal))* )? INTO ( identifier (DELIMITER IN? identifier)? (COUNT IN? identifier)? )+ (WITH? POINTER qualifiedDataName)? (TALLYING IN? qualifiedDataName)? (ON? OVERFLOW statements)? (NOT ON? OVERFLOW statements)? END_UNSTRING? ; // use statement useStatement : USE ( useProcedureClause | useProcedureDebugClause ) ; useProcedureClause : GLOBAL? AFTER STANDARD? ( (EXCEPTION | ERROR) | (BEGINNING | ENDING)? (FILE | REEL | UNIT)? LABEL ) PROCEDURE ON? (fileName+ | INPUT | OUTPUT | I_O | EXTEND) (GIVING dataName+)? ; useProcedureDebugClause : FOR? DEBUGGING ON? ( ALL PROCEDURES | ALL REFERENCES? OF identifier | procedureName+ | fileName+ ) ; // write statement writeStatement : WRITE recordName (FROM (identifier | literal))? writeAdvancingPhrase? (AT? (END_OF_PAGE | EOP) statements)? (NOT AT? (END_OF_PAGE | EOP) statements)? (INVALID KEY? statements)? (NOT INVALID KEY? statements)? END_WRITE? ; writeAdvancingPhrase : (BEFORE | AFTER) ADVANCING? ( PAGE | (identifier | literal) (LINE | LINES)? | mnemonicName ) ; // statement clauses ---------------------------------- onExceptionClause : ON? EXCEPTION statements ; notOnExceptionClause : NOT ON? EXCEPTION statements ; // arithmetic expression ---------------------------------- arithmeticExpression : timesDiv ((PLUSCHAR | MINUSCHAR) timesDiv)* ; timesDiv : power ((ASTERISKCHAR | SLASHCHAR) power)* ; power : (PLUSCHAR | MINUSCHAR)? basis (DOUBLEASTERISKCHAR basis)* ; basis : (identifier | literal | LPARENCHAR arithmeticExpression RPARENCHAR) ; commentEntry : ( ( literal | cobolWord | keyword | AMPCHAR | ASTERISKCHAR | COLONCHAR | COMMACHAR | COMMENTTAG | DOLLARCHAR | DOUBLEQUOTE | DOT | EQUALCHAR | LESSTHANCHAR | LESSTHANOREQUAL | LPARENCHAR | MINUSCHAR | MORETHANCHAR | MORETHANOREQUAL | PLUSCHAR | RPARENCHAR | SINGLEQUOTE | SLASHCHAR )+ DOT )+ ; // logical expressions ---------------------------------- condition : combinableCondition ( (AND | OR) (combinableCondition | abbreviationRest) )* ; combinableCondition : NOT? simpleCondition; simpleCondition : LPARENCHAR condition RPARENCHAR | relationCondition | classCondition | conditionNameCondition ; classCondition : identifier IS? NOT? ( NUMERIC | ALPHABETIC | ALPHABETIC_LOWER | ALPHABETIC_UPPER | className | DBCS | KANJI ) ; conditionNameCondition : conditionNameReference ; conditionNameReference : conditionName ( ((IN | OF) dataName)* ((IN | OF) fileName)? (LPARENCHAR subscript RPARENCHAR)* | ((IN | OF) mnemonicName)* ) ; relationCondition : arithmeticExpression (relationalOperator arithmeticExpression | signCondition) ; signCondition : IS? NOT? (POSITIVE | NEGATIVE | ZERO) ; relationalOperator : (IS | ARE)? ( NOT? ( GREATER THAN? | MORETHANCHAR | LESS THAN? | LESSTHANCHAR | EQUAL TO? | EQUALCHAR ) | GREATER THAN? OR EQUAL TO? | MORETHANOREQUAL | LESS THAN? OR EQUAL TO? | LESSTHANOREQUAL ) ; abbreviationRest : (NOT? relationalOperator? abbreviationLeaf)+ ; abbreviationLeaf : arithmeticExpression | LPARENCHAR arithmeticExpression abbreviationRest RPARENCHAR ; // names ---------------------------------- alphabetName : cobolWord ; assignmentName : systemName ; basisName : programName ; cdName : cobolWord ; className : cobolWord ; computerName : systemName ; conditionName : cobolWord ; dataName : cobolWord ; dataDescName : FILLER | CURSOR | dataName ; environmentName : systemName ; fileName : cobolWord ; functionName : cobolWord | LENGTH | RANDOM | SUM | WHEN_COMPILED ; indexName : cobolWord ; languageName : systemName ; libraryName : cobolWord ; mnemonicName : cobolWord ; paragraphName : cobolWord | integerLiteral ; procedureName : paragraphName ((IN | OF) sectionName)? | sectionName ; programName : cobolWord ; qualifiedDataName : dataName ((IN | OF) (dataName | tableCall))* ((IN | OF) fileName)? | specialRegister ; recordName : qualifiedDataName ; reportName : qualifiedDataName ; routineName : cobolWord ; sectionName : cobolWord | integerLiteral ; systemName : cobolWord ; symbolicCharacter : cobolWord ; specialRegister : ADDRESS OF dataName | DEBUG_ITEM | LENGTH OF identifier | RETURN_CODE | SHIFT_OUT | SHIFT_IN | SORT_CONTROL | SORT_CORE_SIZE | SORT_FILE_SIZE | SORT_MESSAGE | SORT_MODE_SIZE | SORT_RETURN | TALLY | WHEN_COMPILED ; // identifier ---------------------------------- identifier : qualifiedDataName | tableCall | functionCall | linageCounterCall ; // array access tableCall : qualifiedDataName (LPARENCHAR subscript RPARENCHAR)* (LPARENCHAR characterPosition COLONCHAR length? RPARENCHAR)? ; functionCall : FUNCTION functionName (LPARENCHAR argument RPARENCHAR)* (LPARENCHAR characterPosition COLONCHAR length? RPARENCHAR)? ; linageCounterCall : LINAGE_COUNTER ((IN | OF) fileName)? ; length : arithmeticExpression ; characterPosition : arithmeticExpression ; subscript : ( integerLiteral | qualifiedDataName integerLiteral? | indexName integerLiteral? | arithmeticExpression | ALL )+ ; argument : ( literal | identifier | qualifiedDataName integerLiteral? | indexName integerLiteral? | arithmeticExpression )+ ; obsoletePictureStringClause : pictureString ; // literal ---------------------------------- cobolWord : IDENTIFIER; literal : NONNUMERICLITERAL | numericLiteral | booleanLiteral | figurativeConstant; booleanLiteral : TRUE | FALSE; numericLiteral : NUMERICLITERAL | integerLiteral | ZERO; integerLiteral : INTEGERLITERAL | LEVEL_NUMBER_66 | LEVEL_NUMBER_77 | LEVEL_NUMBER_88; figurativeConstant : ALL literal | HIGH_VALUE | HIGH_VALUES | LOW_VALUE | LOW_VALUES | NULL | NULLS | QUOTE | QUOTES | SPACE | SPACES | ZERO | ZEROS | ZEROES ; // keywords ---------------------------------- keyword : ACCEPT | ACCESS | ADD | ADDRESS | ADVANCING | AFTER | ALL | ALPHABET | ALPHABETIC | ALPHABETIC_LOWER | ALPHABETIC_UPPER | ALPHANUMERIC | ALPHANUMERIC_EDITED | ALSO | ALTER | ALTERNATE | AND | ANY | APOST | APPROXIMATE | ARE | AREA | AREAS | ARITH | AS | ASCENDING | ASCII | ASSIGN | AT | AUTHOR | BEFORE | BEGINNING | BINARY | BLANK | BLOCK | BOTTOM | BY | CALL | CANCEL | CD | CF | CH | CHANNEL | CHARACTER | CHARACTERS | CLASS | CLOCK_UNITS | CLOSE | COBOL | CODE | CODEPAGE | CODE_SET | COLLATING | COLUMN | COMMA | COMMITMENT | COMMON | COMMUNICATION | COMP | COMP_1 | COMP_2 | COMP_3 | COMP_4 | COMPUTATIONAL | COMPUTATIONAL_1 | COMPUTATIONAL_2 | COMPUTATIONAL_3 | COMPUTATIONAL_4 | COMPUTE | CONFIGURATION | CONTAINS | CONTENT | CONTINUE | CONTROL | CONTROLS | CONVERTING | COPY | CORR | CORRESPONDING | COUNT | CURRENCY | CURSOR | DATA | DATE | DATE_COMPILED | DATE_WRITTEN | DAY | DAY_OF_WEEK | DBCS | DE | DEBUG_CONTENTS | DEBUG_ITEM | DEBUG_LINE | DEBUG_NAME | DEBUG_SUB_1 | DEBUG_SUB_2 | DEBUG_SUB_3 | DEBUGGING | DECIMAL_POINT | DECLARATIVES | DEFINITION | DELETE | DELIMITED | DELIMITER | DEPENDING | DESCENDING | DESTINATION | DETAIL | DISABLE | DISK | DISPLAY | DISPLAY_1 | DIVIDE | DIVISION | DOWN | DUPLICATES | DYNAMIC | EBCDIC | EGCS | EGI | ELSE | EMI | ENABLE | END | END_ADD | END_CALL | END_COMPUTE | END_DELETE | END_DIVIDE | END_EVALUATE | END_IF | END_MULTIPLY | END_OF_PAGE | END_PERFORM | END_READ | END_RECEIVE | END_RETURN | END_REWRITE | END_SEARCH | END_START | END_STRING | END_SUBTRACT | END_UNSTRING | END_WRITE | ENDING | ENTER | ENTRY | ENVIRONMENT | EOP | EQUAL | ERROR | ESI | EVALUATE | EVERY | EXCEPTION | EXCLUSIVE | EXIT | EXTEND | EXTERNAL | FALSE | FD | FILE | FILE_CONTROL | FILLER | FINAL | FIRST | FOOTING | FOR | FROM | FULL | FUNCTION | GENERATE | GOBACK | GENERIC | GIVING | GLOBAL | GO | GREATER | GROUP | HEADING | HIGH_VALUE | HIGH_VALUES | I_O | I_O_CONTROL | ID | IDENTIFICATION | IF | IMPLICIT | IN | INDEX | INDEXED | INDICATE | INITIAL | INITIALIZE | INITIATE | INPUT | INPUT_OUTPUT | INSPECT | INSTALLATION | INTO | INVALID | IS | JUST | JUSTIFIED | JUSTIFY | KANJI | KEPT | KEY | LABEL | LAST | LEADING | LEFT | LENGTH | LESS | LIB | LIBRARY | LIMIT | LIMITS | LINAGE | LINAGE_COUNTER | LINE | LINES | LINE_COUNTER | LINKAGE | LOCK | LOCKFILE | LOW_VALUE | LOW_VALUES | MEMORY | MERGE | MESSAGE | MODE | MODULES | MORE_LABELS | MOVE | MULTIPLE | MULTIPLY | NATIONAL | NATIVE | NEGATIVE | NEXT | NO | NOSEQ | NOT | NULL | NULLS | NUMBER | NUMERIC | NUMERIC_EDITED | OBJECT_COMPUTER | OCCURS | ODT | OF | OFF | OMITTED | ON | OPEN | OPTIMIZE | OPTIONAL | OR | ORDER | ORGANIZATION | OTHER | OUTPUT | OVERFLOW | PACKED_DECIMAL | PADDING | PAGE | PAGE_COUNTER | PASSWORD | PERFORM | PF | PH | PIC | PICTURE | PLUS | POINTER | POSITION | POSITIVE | PRINTING | PROCEDURE | PROCEDURES | PROCEED | PROCESS | PROGRAM | PROGRAM_ID | PROGRAM_STATUS | PROMPT | PROTECTED | PURGE | QUEUE | QUOTE | QUOTES | RANDOM | RD | READ | RECEIVE | RECEIVE_CONTROL | RECORD | RECORDING | RECORDS | REDEFINES | REEL | REFERENCE | REFERENCES | RELATIVE | RELEASE | REMAINDER | REMOVAL | RENAMES | REPLACE | REPLACING | REPLY | REPORT | REPORTING | REPORTS | RERUN | RESERVE | RESET | RETURN | RETURN_CODE | RETURNED | REVERSED | REWIND | REWRITE | RF | RH | RIGHT | ROUNDED | RUN | SAME | SCREEN | SD | SEARCH | SECTION | SECURITY | SEGMENT | SEGMENT_LIMIT | SELECT | SEND | SENTENCE | SEPARATE | SEQUENCE | SEQUENTIAL | SET | SHARED | SHIFT_IN | SHIFT_OUT | SIGN | SIZE | SORT | SORT_CONTROL | SORT_CORE_SIZE | SORT_FILE_SIZE | SORT_MERGE | SORT_MESSAGE | SORT_MODE_SIZE | SORT_RETURN | SOURCE | SOURCE_COMPUTER | SP | SPACE | SPACES | SPECIAL_NAMES | STANDARD | STANDARD_1 | STANDARD_2 | START | STATUS | STOP | STRING | SUB_QUEUE_1 | SUB_QUEUE_2 | SUB_QUEUE_3 | SUBTRACT | SUM | SUPPRESS | SYMBOLIC | SYNC | SYNCHRONIZED | TABLE | TALLY | TALLYING | TAPE | TERMINAL | TERMINATE | TEST | TEXT | THAN | THEN | THREAD | THROUGH | THRU | TIME | TIMER | TIMES | TO | TOP | TRAILING | TRUE | TYPE | UNIT | UNLOCK | UNLOCKFILE | UNLOCKRECORD | UNSTRING | UNTIL | UP | UPON | USAGE | USE | USING | VALUE | VALUES | VARYING | WAIT | WHEN | WHEN_COMPILED | WITH | WORDS | WORKING_STORAGE | WRITE | XOPTS | YEAR | YYYYMMDD | YYYYDDD | ZERO | ZEROS| ZEROES ; // lexer rules -------------------------------------------------------------------------------- // keywords ACCEPT : A C C E P T; ACCESS : A C C E S S; ADD : A D D; ADDRESS : A D D R E S S; ADVANCING : A D V A N C I N G; AFTER : A F T E R; ALL : A L L; ALPHABET : A L P H A B E T; ALPHABETIC : A L P H A B E T I C; ALPHABETIC_LOWER : A L P H A B E T I C MINUSCHAR L O W E R; ALPHABETIC_UPPER : A L P H A B E T I C MINUSCHAR U P P E R; ALPHANUMERIC : A L P H A N U M E R I C; ALPHANUMERIC_EDITED : A L P H A N U M E R I C MINUSCHAR E D I T E D; ALSO : A L S O; ALTER : A L T E R; ALTERNATE : A L T E R N A T E; AND : A N D; ANY : A N Y; APOST : A P O S T; APPROXIMATE : A P P R O X I M A T E; ARE : A R E; AREA : A R E A; AREAS : A R E A S; ARITH : A R I T H; AS : A S; ASCENDING : A S C E N D I N G; ASCII : A S C I I; ASSIGN : A S S I G N; AT : A T; AUTHOR : A U T H O R; BEFORE : B E F O R E; BEGINNING : B E G I N N I N G; BINARY : B I N A R Y; BLANK : B L A N K; BLOCK : B L O C K; BOTTOM : B O T T O M; BY : B Y; CALL : C A L L; CANCEL : C A N C E L; CD : C D; CF : C F; CH : C H; CHANNEL : C H A N N E L; CHARACTER : C H A R A C T E R; CHARACTERS : C H A R A C T E R S; CLASS : C L A S S; CLOCK_UNITS : C L O C K MINUSCHAR U N I T S; CLOSE : C L O S E; COBOL : C O B O L; CODE : C O D E; CODEPAGE : C O D E P A G E; CODE_SET : C O D E MINUSCHAR S E T; COLLATING : C O L L A T I N G; COLUMN : C O L U M N; COMMA : C O M M A; COMMITMENT : C O M M I T M E N T; COMMON : C O M M O N; COMMUNICATION : C O M M U N I C A T I O N; COMP : C O M P; COMP_1 : C O M P MINUSCHAR '1'; COMP_2 : C O M P MINUSCHAR '2'; COMP_3 : C O M P MINUSCHAR '3'; COMP_4 : C O M P MINUSCHAR '4'; COMPUTATIONAL : C O M P U T A T I O N A L; COMPUTATIONAL_1 : C O M P U T A T I O N A L MINUSCHAR '1'; COMPUTATIONAL_2 : C O M P U T A T I O N A L MINUSCHAR '2'; COMPUTATIONAL_3 : C O M P U T A T I O N A L MINUSCHAR '3'; COMPUTATIONAL_4 : C O M P U T A T I O N A L MINUSCHAR '4'; COMPUTE : C O M P U T E; CONFIGURATION : C O N F I G U R A T I O N; CONTAINS : C O N T A I N S; CONTENT : C O N T E N T; CONTINUE : C O N T I N U E; CONTROL : C O N T R O L; CONTROLS : C O N T R O L S; CONVERTING : C O N V E R T I N G; COPY : C O P Y; CORR : C O R R; CORRESPONDING : C O R R E S P O N D I N G; COUNT : C O U N T; CURRENCY : C U R R E N C Y; CURSOR : C U R S O R; DATA : D A T A; DATE : D A T E; DATE_COMPILED : D A T E MINUSCHAR C O M P I L E D; DATE_WRITTEN : D A T E MINUSCHAR W R I T T E N; DAY : D A Y; DAY_OF_WEEK : D A Y MINUSCHAR O F MINUSCHAR W E E K; DBCS : D B C S; DE : D E; DEBUG_CONTENTS : D E B U G MINUSCHAR C O N T E N T S; DEBUG_ITEM : D E B U G MINUSCHAR I T E M; DEBUG_LINE : D E B U G MINUSCHAR L I N E; DEBUG_NAME : D E B U G MINUSCHAR N A M E; DEBUG_SUB_1 : D E B U G MINUSCHAR S U B MINUSCHAR '1'; DEBUG_SUB_2 : D E B U G MINUSCHAR S U B MINUSCHAR '2'; DEBUG_SUB_3 : D E B U G MINUSCHAR S U B MINUSCHAR '3'; DEBUGGING : D E B U G G I N G; DECIMAL_POINT : D E C I M A L MINUSCHAR P O I N T; DECLARATIVES : D E C L A R A T I V E S; DEFINITION : D E F I N I T I O N; DELETE : D E L E T E; DELIMITED : D E L I M I T E D; DELIMITER : D E L I M I T E R; DEPENDING : D E P E N D I N G; DESCENDING : D E S C E N D I N G; DESTINATION : D E S T I N A T I O N; DETAIL : D E T A I L; DISABLE : D I S A B L E; DISK : D I S K; DISPLAY : D I S P L A Y; DISPLAY_1 : D I S P L A Y MINUSCHAR '1'; DIVIDE : D I V I D E; DIVISION : D I V I S I O N; DOWN : D O W N; DUPLICATES : D U P L I C A T E S; DYNAMIC : D Y N A M I C; EBCDIC : E B C D I C; EGCS : E G C S; // E X T E N S I O N EGI : E G I; ELSE : E L S E; EMI : E M I; ENABLE : E N A B L E; END : E N D; END_ADD : E N D MINUSCHAR A D D; END_CALL : E N D MINUSCHAR C A L L; END_COMPUTE : E N D MINUSCHAR C O M P U T E; END_DELETE : E N D MINUSCHAR D E L E T E; END_DIVIDE : E N D MINUSCHAR D I V I D E; END_EVALUATE : E N D MINUSCHAR E V A L U A T E; END_IF : E N D MINUSCHAR I F; END_MULTIPLY : E N D MINUSCHAR M U L T I P L Y; END_OF_PAGE : E N D MINUSCHAR O F MINUSCHAR P A G E; END_PERFORM : E N D MINUSCHAR P E R F O R M; END_READ : E N D MINUSCHAR R E A D; END_RECEIVE : E N D MINUSCHAR R E C E I V E; END_RETURN : E N D MINUSCHAR R E T U R N; END_REWRITE : E N D MINUSCHAR R E W R I T E; END_SEARCH : E N D MINUSCHAR S E A R C H; END_START : E N D MINUSCHAR S T A R T; END_STRING : E N D MINUSCHAR S T R I N G; END_SUBTRACT : E N D MINUSCHAR S U B T R A C T; END_UNSTRING : E N D MINUSCHAR U N S T R I N G; END_WRITE : E N D MINUSCHAR W R I T E; ENDING : E N D I N F; ENTER : E N T E R; ENTRY : E N T R Y; ENVIRONMENT : E N V I R O N M E N T; EOP : E O P; EQUAL : E Q U A L; ERROR : E R R O R; ESI : E S I; EVALUATE : E V A L U A T E; EVERY : E V E R Y; EXCEPTION : E X C E P T I O N; EXCLUSIVE : E X C L U S I V E; EXIT : E X I T; EXTEND : E X T E N D; EXTERNAL : E X T E R N A L; FALSE : F A L S E; FD : F D; FILE : F I L E; FILE_CONTROL : F I L E MINUSCHAR C O N T R O L; FILLER : F I L L E R; FINAL : F I N A L; FIRST : F I R S T; FOOTING : F O O T I N G; FOR : F O R; FROM : F R O M; FULL : F U L L; FUNCTION : F U N C T I O N; GENERATE : G E N E R A T E; GOBACK : G O B A C K; GENERIC : G E N E R I C; GIVING : G I V I N G; GLOBAL : G L O B A L; GO : G O; GREATER : G R E A T E R; GROUP : G R O U P; HEADING : H E A D I N G; HIGH_VALUE : H I G H MINUSCHAR V A L U E; HIGH_VALUES : H I G H MINUSCHAR V A L U E S; I_O : I MINUSCHAR O; I_O_CONTROL : I MINUSCHAR O MINUSCHAR C O N T R O L; ID : I D; IDENTIFICATION : I D E N T I F I C A T I O N; IF : I F; IMPLICIT : I M P L I C I T; IN : I N; INDEX : I N D E X; INDEXED : I N D E X E D; INDICATE : I N D I C A T E; INITIAL : I N I T I A L; INITIALIZE : I N I T I A L I Z E; INITIATE : I N I T I A T E; INPUT : I N P U T; INPUT_OUTPUT : I N P U T MINUSCHAR O U T P U T; INSPECT : I N S P E C T; INSTALLATION : I N S T A L L A T I O N; INTO : I N T O; INVALID : I N V A L I D; IS : I S; JUST : J U S T; JUSTIFIED : J U S T I F I E D; JUSTIFY : J U S T I F Y; KANJI : K A N J I; KEPT : K E P T; KEY : K E Y; LABEL : L A B E L; LAST : L A S T; LEADING : L E A D I N G; LEFT : L E F T; LENGTH : L E N G T H; LESS : L E S S; LIB : L I B; LIBRARY : L I B R A R Y; LIMIT : L I M I T; LIMITS : L I M I T S; LINAGE : L I N A G E; LINAGE_COUNTER : L I N A G E '_' C O U N T E R; LINE : L I N E; LINES : L I N E S; LINE_COUNTER : L I N E MINUSCHAR C O U N T E R; LINKAGE : L I N K A G E; LOCK : L O C K; LOCKFILE : L O C K F I L E; LOW_VALUE : L O W MINUSCHAR V A L U E; LOW_VALUES : L O W MINUSCHAR V A L U E S; MEMORY : M E M O R Y; MERGE : M E R G E; MESSAGE : M E S S A G E; MODE : M O D E; MODULES : M O D U L E S; MORE_LABELS : M O R E MINUSCHAR L A B E L S; MOVE : M O V E; MULTIPLE : M U L T I P L E; MULTIPLY : M U L T I P L Y; NATIONAL : N A T I O N A L; NATIVE : N A T I V E; NEGATIVE : N E G A T I V E; NEXT : N E X T; NO : N O; NOSEQ : N O S E Q; NOSTDTRUNC : N O S T D T R U N C; NOT : N O T; NULL : N U L L; NULLS : N U L L S; NUMBER : N U M B E R; NUMERIC : N U M E R I C; NUMERIC_EDITED : N U M E R I C MINUSCHAR E D I T E D; OBJECT_COMPUTER : O B J E C T MINUSCHAR C O M P U T E R; OCCURS : O C C U R S; ODT : O D T; OF : O F; OFF : O F F; OMITTED : O M I T T E D; ON : O N; OPEN : O P E N; OPTIMIZE : O P T I M I Z E; OPTIONAL : O P T I O N A L; OR : O R; ORDER : O R D E R; ORGANIZATION : O R G A N I Z A T I O N; OTHER : O T H E R; OUTPUT : O U T P U T; OVERFLOW : O V E R F L O W; PACKED_DECIMAL : P A C K E D MINUSCHAR D E C I M A L; PADDING : P A D D I N G; PAGE : P A G E; PAGE_COUNTER : P A G E MINUSCHAR C O U N T E R; PASSWORD : P A S S W O R D; PERFORM : P E R F O R M; PF : P F; PH : P H; PIC : P I C; PICTURE : P I C T U R E; PLUS : P L U S; POINTER : P O I N T E R; POSITION : P O S I T I O N; POSITIVE : P O S I T I V E; PRINTING : P R I N T I N G; PROCEDURE : P R O C E D U R E; PROCEDURES : P R O C E D U R E S; PROCEED : P R O C E E D; PROCESS : P R O C E S S; PROGRAM : P R O G R A M; PROGRAM_ID : P R O G R A M MINUSCHAR I D; PROGRAM_STATUS : P R O G R A M MINUSCHAR S T A T U S; PROMPT : P R O M P T; PROTECTED : P R O T E C T E D; PURGE : P U R G E; QUEUE : Q U E U E; QUOTE : Q U O T E; QUOTES : Q U O T E S; RANDOM : R A N D O M; RD : R D; READ : R E A D; RECEIVE : R E C E I V E; RECEIVE_CONTROL : R E C E I V E MINUSCHAR C O N T R O L; RECORD : R E C O R D; RECORDING : R E C O R D I N G; RECORDS : R E C O R D S; REDEFINES : R E D E F I N E S; REEL : R E E L; REFERENCE : R E F E R E N C E; REFERENCES : R E F E R E N C E S; RELATIVE : R E L A T I V E; RELEASE : R E L E A S E; REMAINDER : R E M A I N D E R; REMOVAL : R E M O V A L; RENAMES : R E N A M E S; REPLACE : R E P L A C E; REPLACING : R E P L A C I N G; REPLY : R E P L Y; // TANDEM EXTENSION REPORT : R E P O R T; REPORTING : R E P O R T I N G; REPORTS : R E P O R T S; RERUN : R E R U N; RESERVE : R E S E R V E; RESET : R E S E T; RETURN : R E T U R N; RETURN_CODE : R E T U R N MINUSCHAR C O D E; RETURNED : R E T U R N E D; REVERSED : R E V E R S E D; REWIND : R E W I N D; REWRITE : R E W R I T E; RF : R F; RH : R H; RIGHT : R I G H T; ROUNDED : R O U N D E D; RUN : R U N; SAME : S A M E; SCREEN : S C R E E N; SD : S D; SEARCH : S E A R C H; SECTION : S E C T I O N; SECURITY : S E C U R I T Y; SEGMENT : S E G M E N T; SEGMENT_LIMIT : S E G M E N T MINUSCHAR L I M I T; SELECT : S E L E C T; SEND : S E N D; SENTENCE : S E N T E N C E; SEPARATE : S E P A R A T E; SEQUENCE : S E Q U E N C E; SEQUENTIAL : S E Q U E N T I A L; SET : S E T; SHARED : S H A R E D; SHIFT_IN : S H I F T MINUSCHAR I N; SHIFT_OUT : S H I F T MINUSCHAR O U T; SIGN : S I G N; SIZE : S I Z E; SORT : S O R T; SORT_CONTROL : S O R T MINUSCHAR C O N T R O L; SORT_CORE_SIZE : S O R T MINUSCHAR C O R E MINUSCHAR S I Z E; SORT_FILE_SIZE : S O R T MINUSCHAR F I L E MINUSCHAR S I Z E; SORT_MERGE : S O R T MINUSCHAR M E R G E; SORT_MESSAGE : S O R T MINUSCHAR M E S S A G E; SORT_MODE_SIZE : S O R T MINUSCHAR M O D E MINUSCHAR S I Z E; SORT_RETURN : S O R T MINUSCHAR R E T U R N; SOURCE : S O U R C E; SOURCE_COMPUTER : S O U R C E MINUSCHAR C O M P U T E R; SP : S P; SPACE : S P A C E; SPACES : S P A C E S; SPECIAL_NAMES : S P E C I A L MINUSCHAR N A M E S; STANDARD : S T A N D A R D; STANDARD_1 : S T A N D A R D MINUSCHAR '1'; STANDARD_2 : S T A N D A R D MINUSCHAR '2'; START : S T A R T; STATUS : S T A T U S; STOP : S T O P; STRING : S T R I N G; SUB_QUEUE_1 : S U B MINUSCHAR Q U E U E MINUSCHAR '1'; SUB_QUEUE_2 : S U B MINUSCHAR Q U E U E MINUSCHAR '2'; SUB_QUEUE_3 : S U B MINUSCHAR Q U E U E MINUSCHAR '3'; SUBTRACT : S U B T R A C T; SUM : S U M; SUPPRESS : S U P P R E S S; SYMBOLIC : S Y M B O L I C; SYNC : S Y N C; SYNCHRONIZED : S Y N C H R O N I Z E D; TABLE : T A B L E; TALLY : T A L L Y; TALLYING : T A L L Y I N G; TAPE : T A P E; TERMINAL : T E R M I N A L; TERMINATE : T E R M I N A T E; TEST : T E S T; TEXT : T E X T; THAN : T H A N; THEN : T H E N; THREAD : T H R E A D; THROUGH : T H R O U G H; THRU : T H R U; TIME : T I M E; TIMER : T I M E R; TIMES : T I M E S; TO : T O; TOP : T O P; TRAILING : T R A I L I N G; TRUE : T R U E; TYPE : T Y P E; UNIT : U N I T; UNLOCK : U N L O C K; UNLOCKFILE : U N L O C K F I L E; UNLOCKRECORD : U N L O C K R E C O R D; UNSTRING : U N S T R I N G; UNTIL : U N T I L; UP : U P; UPON : U P O N; USAGE : U S A G E; USE : U S E; USING : U S I N G; VALUE : V A L U E; VALUES : V A L U E S; VARYING : V A R Y I N G; WAIT : W A I T; WHEN : W H E N; WHEN_COMPILED : W H E N MINUSCHAR C O M P I L E D; WITH : W I T H; WORDS : W O R D S; WORKING_STORAGE : W O R K I N G MINUSCHAR S T O R A G E; WRITE : W R I T E; XOPTS: X O P T S; YEAR : Y E A R; YYYYMMDD : Y Y Y Y M M D D; YYYYDDD : Y Y Y Y D D D; ZERO : Z E R O; ZEROS : Z E R O S; ZEROES : Z E R O E S; // symbols AMPCHAR : '&'; ASTERISKCHAR : '*'; DOUBLEASTERISKCHAR : '**'; COLONCHAR : ':'; COMMACHAR : ','; COMMENTTAG : '>*'; DOLLARCHAR : '$'; DOUBLEQUOTE : '""'; DOT : '.'; EQUALCHAR : '='; LESSTHANCHAR : '<'; LESSTHANOREQUAL : '<='; LPARENCHAR : '('; MINUSCHAR : '-'; MORETHANCHAR : '>'; MORETHANOREQUAL : '>='; PLUSCHAR : '+'; SINGLEQUOTE : '\\''; RPARENCHAR : ')'; SLASHCHAR : '/'; // literals NONNUMERICLITERAL : STRINGLITERAL | DBCSLITERAL | HEXNUMBER; fragment HEXNUMBER : X '""' [0-9A-F]+ '""' | X '\\'' [0-9A-F]+ '\\'' ; fragment STRINGLITERAL : '""' (~[""\\n\\r] | '""""' | '\\'')* '""' | '\\'' (~['\\n\\r] | '\\'\\'' | '""')* '\\'' ; fragment DBCSLITERAL : [GN] '""' (~[""\\n\\r] | '""""' | '\\'')* '""' | [GN] '\\'' (~['\\n\\r] | '\\'\\'' | '""')* '\\'' ; LEVEL_NUMBER_66 : '66'; LEVEL_NUMBER_77 : '77'; LEVEL_NUMBER_88 : '88'; INTEGERLITERAL : (PLUSCHAR | MINUSCHAR)? [0-9]+; NUMERICLITERAL : (PLUSCHAR | MINUSCHAR)? [0-9]* (DOT | COMMACHAR) [0-9]+ (('e' | 'E') (PLUSCHAR | MINUSCHAR)? [0-9]+)?; IDENTIFIER : [a-zA-Z0-9]+ ([-_]+ [a-zA-Z0-9]+)*; // whitespace, line breaks, comments, ... NEWLINE : '\\r'? '\\n' -> skip; COMMENTLINE : COMMENTTAG ~('\\n' | '\\r')* -> skip; WS : [ \\t\\f;]+ -> skip; SEPARATOR : ', ' -> skip; // case insensitive chars fragment A:('a'|'A'); fragment B:('b'|'B'); fragment C:('c'|'C'); fragment D:('d'|'D'); fragment E:('e'|'E'); fragment F:('f'|'F'); fragment G:('g'|'G'); fragment H:('h'|'H'); fragment I:('i'|'I'); fragment J:('j'|'J'); fragment K:('k'|'K'); fragment L:('l'|'L'); fragment M:('m'|'M'); fragment N:('n'|'N'); fragment O:('o'|'O'); fragment P:('p'|'P'); fragment Q:('q'|'Q'); fragment R:('r'|'R'); fragment S:('s'|'S'); fragment T:('t'|'T'); fragment U:('u'|'U'); fragment V:('v'|'V'); fragment W:('w'|'W'); fragment X:('x'|'X'); fragment Y:('y'|'Y'); fragment Z:('z'|'Z');",16191,True,3061.6757595581244,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.preloaders { import flash.display.DisplayObject; import flash.display.GradientType; import flash.display.Graphics; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.TimerEvent; import flash.geom.Matrix; import flash.geom.Rectangle; import flash.net.URLRequest; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.text.TextField; import flash.text.TextFormat; import flash.utils.Timer; import flash.utils.getDefinitionByName; import flash.utils.getTimer; import mx.events.FlexEvent; import mx.events.RSLEvent; import mx.geom.RoundedRectangle; import mx.graphics.RectangularDropShadow; /** * The DownloadProgressBar class displays download progress. * It is used by the Preloader control to provide user feedback * while the application is downloading and loading. * *

The download progress bar displays information about * two different phases of the application: * the download phase and the initialization phase.

* *

In the Application container, use the * the preloader property to specify the name of your subclass.

* *

You can implement a custom download progress bar component * by creating a subclass of the DownloadProgressBar class. * Do not implement a download progress bar as an MXML component * because it loads too slowly.

* * @see mx.core.Application * @see mx.preloaders.IPreloaderDisplay * @see mx.preloaders.Preloader * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DownloadProgressBar extends Sprite implements IPreloaderDisplay { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function DownloadProgressBar() { super(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * The minimum number of milliseconds * that the display should appear visible. * If the downloading and initialization of the application * takes less time than this value, then Flex pauses for this amount * of time before dispatching the complete event. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var MINIMUM_DISPLAY_TIME:uint = 0; /** * The percentage of the progress bar that the downloading phase * fills when the SWF file is fully downloaded. * The rest of the progress bar is filled during the initializing phase. * This should be a value from 0 to 100. * * @default 60 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var DOWNLOAD_PERCENTAGE:uint = 60; /** * @private */ private var _showProgressBar:Boolean = true; /** * @private * Cached Rectangle returned by the labelRect getter. */ private var _labelRect:Rectangle = labelRect; /** * @private * Cached Rectangle returned by the percentRect getter. */ private var _percentRect:Rectangle = percentRect; /** * @private * Cached RoundedRectangle returned by the borderRect getter. */ private var _borderRect:RoundedRectangle = borderRect; /** * @private * Cached RoundedRectangle returned by the barFrameRect getter. */ private var _barFrameRect:RoundedRectangle = barFrameRect; /** * @private * Cached RoundedRectangle returned by the barRect getter. */ private var _barRect:RoundedRectangle = barRect; /** * @private */ private var _xOffset:Number = 20; /** * @private */ private var _yOffset:Number = 20; /** * @private */ private var _maximum:Number = 0; /** * @private */ private var _value:Number = 0; /** * @private */ private var _barSprite:Sprite; /** * @private */ private var _barFrameSprite:Sprite; /** * @private */ private var _labelObj:TextField; /** * @private */ private var _percentObj:TextField; /** * @private */ private var _startTime:int; /** * @private */ private var _displayTime:int; /** * @private */ private var _startedLoading:Boolean = false; /** * @private */ private var _startedInit:Boolean = false; /** * @private */ private var _showingDisplay:Boolean = false; /** * @private */ private var _displayStartCount:uint = 0; /** * @private */ private var _initProgressCount:uint = 0; /** * The total number of validation events you expect to get * in the initializing phase. This should be an integer * greater or equal to 4 (and note that if it is greater than 4 * you might have an inefficiency in your initialization code) * * @default 6 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 4 */ protected var initProgressTotal:uint = 6; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // visible //---------------------------------- /** * @private * Storage for the visible property. */ private var _visible:Boolean = false; /** * Specifies whether the download progress bar is visible. * *

When the Preloader control determines that the progress bar should be displayed, * it sets this value to true. When the Preloader control determines that * the progress bar should be hidden, it sets the value to false.

* *

A subclass of the DownloadProgressBar class should never modify this property. * Instead, you can override the setter method to recognize when * the Preloader control modifies it, and perform any necessary actions.

* * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function get visible():Boolean { return _visible; } /** * @private */ override public function set visible(value:Boolean):void { if (!_visible && value) show(); else if (_visible && !value ) hide(); _visible = value; } //-------------------------------------------------------------------------- // // Properties: IPreloaderDisplay // //-------------------------------------------------------------------------- //---------------------------------- // backgroundAlpha //---------------------------------- /** * @private * Storage for the backgroundAlpha property. */ private var _backgroundAlpha:Number = 1; /** * Alpha level of the SWF file or image defined by * the backgroundImage property, or the color defined by * the backgroundColor property. * Valid values range from 0 to 1.0. * *

You can specify either a backgroundColor * or a backgroundImage, but not both.

* * @default 1.0 * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get backgroundAlpha():Number { if (!isNaN(_backgroundAlpha)) return _backgroundAlpha; else return 1; } /** * @private */ public function set backgroundAlpha(value:Number):void { _backgroundAlpha = value; } //---------------------------------- // backgroundColor //---------------------------------- /** * @private * Storage for the backgroundColor property. */ private var _backgroundColor:uint; /** * Background color of a download progress bar. * You can have either a backgroundColor or a * backgroundImage, but not both. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get backgroundColor():uint { return _backgroundColor; } /** * @private */ public function set backgroundColor(value:uint):void { _backgroundColor = value; } //---------------------------------- // backgroundImage //---------------------------------- /** * @private * Storage for the backgroundImage property. */ private var _backgroundImage:Object; /** * The background image of the application, * which is passed in by the preloader. * You can specify either a backgroundColor * or a backgroundImage, but not both. * *

A value of null means ""not set"". * If this style and the backgroundColor style are undefined, * the component has a transparent background.

* *

The preloader does not display embedded images. * You can only use images loaded at runtime.

* * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get backgroundImage():Object { return _backgroundImage; } /** * @private */ public function set backgroundImage(value:Object):void { _backgroundImage = value; } //---------------------------------- // backgroundSize //---------------------------------- /** * @private * Storage for the backgroundSize property. */ private var _backgroundSize:String = """"; /** * Scales the image specified by backgroundImage * to different percentage sizes. * A value of ""100%"" stretches the image * to fit the entire component. * To specify a percentage value, you must include the percent sign (%). * A value of ""auto"", maintains * the original size of the image. * * @default ""auto"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get backgroundSize():String { return _backgroundSize; } /** * @private */ public function set backgroundSize(value:String):void { _backgroundSize = value; } //---------------------------------- // preloader //---------------------------------- /** * @private * Storage for the preloader property. */ private var _preloader:Sprite; /** * The Preloader class passes in a reference to itself to the display class * so that it can listen for events from the preloader. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function set preloader(value:Sprite):void { _preloader = value; value.addEventListener(ProgressEvent.PROGRESS, progressHandler); value.addEventListener(Event.COMPLETE, completeHandler); value.addEventListener(RSLEvent.RSL_PROGRESS, rslProgressHandler); value.addEventListener(RSLEvent.RSL_COMPLETE, rslCompleteHandler); value.addEventListener(RSLEvent.RSL_ERROR, rslErrorHandler); value.addEventListener(FlexEvent.INIT_PROGRESS, initProgressHandler); value.addEventListener(FlexEvent.INIT_COMPLETE, initCompleteHandler); } //---------------------------------- // stageHeight //---------------------------------- /** * @private * Storage for the stageHeight property. */ private var _stageHeight:Number = 375; /** * The height of the stage, * which is passed in by the Preloader class. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get stageHeight():Number { return _stageHeight; } /** * @private */ public function set stageHeight(value:Number):void { _stageHeight = value; } //---------------------------------- // stageWidth //---------------------------------- /** * @private * Storage for the stageHeight property. */ private var _stageWidth:Number = 500; /** * The width of the stage, * which is passed in by the Preloader class. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get stageWidth():Number { return _stageWidth; } /** * @private */ public function set stageWidth(value:Number):void { _stageWidth = value; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // barFrameRect //---------------------------------- /** * The dimensions of the progress bar border. * This is a read-only property which you must override * if you need to change it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get barFrameRect():RoundedRectangle { return new RoundedRectangle(14, 40, 154, 4); } //---------------------------------- // barRect //---------------------------------- /** * The dimensions of the progress bar. * This is a read-only property which you must override * if you need to change it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get barRect():RoundedRectangle { return new RoundedRectangle(14, 39, 154, 6, 0); } //---------------------------------- // borderRect //---------------------------------- /** * The dimensions of the border of the display. * This is a read-only property which you must override * if you need to change it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get borderRect():RoundedRectangle { return new RoundedRectangle(0, 0, 182, 60, 4); } //---------------------------------- // downloadingLabel //---------------------------------- /** * @private * Storage for the downloadingLabel property. */ private var _downloadingLabel:String = ""Loading""; /** * The string to display as the label while in the downloading phase. * * @default ""Loading"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get downloadingLabel():String { return _downloadingLabel; } /** * @private */ protected function set downloadingLabel(value:String):void { _downloadingLabel = value; } //---------------------------------- // initializingLabel //---------------------------------- /** * @private * Storage for the initializingLabel property. */ private static var _initializingLabel:String = ""Initializing""; /** * The string to display as the label while in the initializing phase. * * @default ""Initializing"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get initializingLabel():String { return _initializingLabel; } /** * @private */ public static function set initializingLabel(value:String):void { _initializingLabel = value; } //---------------------------------- // label //---------------------------------- /** * @private * Storage for the label property. */ private var _label:String = """"; /** * Text to display when the progress bar is active. * The Preloader class sets this value * before displaying the progress bar. * Implementing this property in a subclass is optional. * * @default """" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get label():String { return _label; } /** * @private */ protected function set label(value:String):void { if (!(value is Function)) _label = value; draw(); } //---------------------------------- // labelFormat //---------------------------------- /** * The TextFormat object of the TextField component of the label. * This is a read-only property which you must override * if you need to change it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get labelFormat():TextFormat { var tf:TextFormat = new TextFormat(); tf.color = 0x333333; tf.font = ""Verdana""; tf.size = 10; return tf; } //---------------------------------- // labelRect //---------------------------------- /** * The dimensions of the TextField component for the label. * This is a read-only property which you must override * if you need to change it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get labelRect():Rectangle { return new Rectangle(14, 17, 100, 16); } //---------------------------------- // percentFormat //---------------------------------- /** * The TextFormat of the TextField component for displaying the percent. * This is a read-only property which you must override * if you need to change it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get percentFormat():TextFormat { var tf:TextFormat = new TextFormat(); tf.align = ""right""; tf.color = 0x000000; tf.font = ""Verdana""; tf.size = 10; return tf; } //---------------------------------- // percentRect //---------------------------------- /** * The dimensions of the TextField component for displaying the percent. * This is a read-only property which you must override * if you need to change it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get percentRect():Rectangle { return new Rectangle(108, 4, 34, 16); } //---------------------------------- // showLabel //---------------------------------- /** * @private * Storage for the showLabel property. */ private var _showLabel:Boolean = true; /** * Controls whether to display the label, true, * or not, false. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get showLabel():Boolean { return _showLabel; } /** * @private */ protected function set showLabel(value:Boolean):void { _showLabel = value; draw(); } //---------------------------------- // showPercentage //---------------------------------- /** * @private * Storage for the showPercentage property. */ private var _showPercentage:Boolean = false; /** * Controls whether to display the percentage, true, * or not, false. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get showPercentage():Boolean { return _showPercentage; } /** * @private */ protected function set showPercentage(value:Boolean):void { _showPercentage = value; draw(); } //-------------------------------------------------------------------------- // // Methods:IPreloaderDisplay // //-------------------------------------------------------------------------- /** * Called by the Preloader after the download progress bar * has been added as a child of the Preloader. * This should be the starting point for configuring your download progress bar. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function initialize():void { _startTime = getTimer(); center(stageWidth, stageHeight); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Centers the download progress bar based on the passed in dimensions. * * @param width The width of the area in which to center the download progress bar. * * @param height The height of the area in which to center the download progress bar. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function center(width:Number, height:Number):void { _xOffset = Math.floor((width - _borderRect.width) / 2); _yOffset = Math.floor((height - _borderRect.height) / 2); } /** * @private * Updates the display. */ private function draw():void { var percentage:Number; if (_startedLoading) { if (!_startedInit) { // 0 to MaxDL Percentage percentage = Math.round(getPercentLoaded(_value, _maximum) * DOWNLOAD_PERCENTAGE / 100); } else { // MaxDL percentage to 100 percentage = Math.round((getPercentLoaded(_value, _maximum) * (100 - DOWNLOAD_PERCENTAGE) / 100) + DOWNLOAD_PERCENTAGE); } } else { percentage = getPercentLoaded(_value, _maximum); } if (_labelObj) _labelObj.text = _label; if (_percentObj) { if (!_showPercentage) { _percentObj.visible = false; _percentObj.text = """"; } else { _percentObj.text = String(percentage) + ""%""; } } if (_barSprite && _barFrameSprite) { if (!_showProgressBar) { _barSprite.visible = false; _barFrameSprite.visible = false; } else { drawProgressBar(percentage); } } } /** * Creates the subcomponents of the display. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function createChildren():void { var g:Graphics = graphics; var labelObj:TextField; var percentObj:TextField; // Draw the background first // Same value as StyleManager.NOT_A_COLOR. However, we don't want to bring in StyleManager at this point. if (backgroundColor != 0xFFFFFFFF) { g.beginFill(backgroundColor, backgroundAlpha); g.drawRect(0, 0, stageWidth, stageHeight); } if (backgroundImage != null) loadBackgroundImage(backgroundImage); _barFrameSprite = new Sprite(); _barSprite = new Sprite(); addChild(_barFrameSprite); addChild(_barSprite); // Draw the outside border and fill. g.beginFill(0xCCCCCC, 0.4); g.drawRoundRect(calcX(_borderRect.x), calcY(_borderRect.y), _borderRect.width, _borderRect.height, _borderRect.cornerRadius * 2, _borderRect.cornerRadius * 2); g.drawRoundRect(calcX(_borderRect.x + 1), calcY(_borderRect.y + 1), _borderRect.width - 2, _borderRect.height - 2, _borderRect.cornerRadius - 1 * 2, _borderRect.cornerRadius - 1 * 2); g.endFill(); g.beginFill(0xCCCCCC,0.4); g.drawRoundRect(calcX(_borderRect.x + 1), calcY(_borderRect.y + 1), _borderRect.width - 2, _borderRect.height - 2, _borderRect.cornerRadius - 1 * 2, _borderRect.cornerRadius - 1 * 2); g.endFill(); var frame_g:Graphics = _barFrameSprite.graphics; // Draw the bar frame border and fill var matrix:Matrix = new Matrix(); matrix.createGradientBox(_barFrameRect.width, _barFrameRect.height, Math.PI / 2, calcX(_barFrameRect.x), calcY(_barFrameRect.y)); frame_g.beginGradientFill(GradientType.LINEAR, [ 0x5C6266, 0xB5B8BA ], [ 1.0, 1.0 ], [ 0, 0xFF ], matrix); frame_g.drawRoundRect(calcX(_barFrameRect.x), calcY(_barFrameRect.y), _barFrameRect.width, _barFrameRect.height, _barFrameRect.cornerRadius * 2, _barFrameRect.cornerRadius * 2); frame_g.drawRoundRect(calcX(_barFrameRect.x + 1), calcY(_barFrameRect.y + 1), _barFrameRect.width - 2, _barFrameRect.height - 2, _barFrameRect.cornerRadius * 2, _barFrameRect.cornerRadius * 2); frame_g.endFill(); // Attach the label TextField. _labelObj = new TextField(); _labelObj.x = calcX(_labelRect.x); _labelObj.y = calcY(_labelRect.y); _labelObj.width = _labelRect.width; _labelObj.height = _labelRect.height; _labelObj.selectable = false; _labelObj.defaultTextFormat = labelFormat; addChild(_labelObj); // Attach the percentage TextField. _percentObj = new TextField(); _percentObj.x = calcX(_percentRect.x); _percentObj.y = calcY(_percentRect.y); _percentObj.width = _percentRect.width; _percentObj.height = _percentRect.height; _percentObj.selectable = false; _percentObj.defaultTextFormat = percentFormat; addChild(_percentObj); // Create dropshadow var ds:RectangularDropShadow = new RectangularDropShadow(); ds.color = 0x000000; ds.angle = 90; ds.alpha = .6; ds.distance = 2; ds.tlRadius = ds.trRadius = ds.blRadius = ds.brRadius = _borderRect.cornerRadius; ds.drawShadow(g, calcX(_borderRect.x), calcY(_borderRect.y), _borderRect.width, _borderRect.height); // Draw the top line g.lineStyle(1,0xFFFFFF, .3); g.moveTo(calcX(_borderRect.x) + _borderRect.cornerRadius, calcY(_borderRect.y)); g.lineTo(calcX(_borderRect.x) - _borderRect.cornerRadius + _borderRect.width, calcY(_borderRect.y)); } /** * @private * Draws the progress bar. */ private function drawProgressBar(percentage:Number):void { var g:Graphics = _barSprite.graphics; g.clear(); var colors:Array = [ 0xFFFFFF, 0xFFFFFF ]; var ratios:Array = [ 0, 0xFF ]; var matrix:Matrix = new Matrix(); // Middle var barWidth:Number = _barRect.width * percentage / 100; var barWidthSplit:Number = barWidth / 2; var barHeight:Number = _barRect.height-4; var barX:Number = calcX(_barRect.x); var barY:Number = calcY(_barRect.y) + 2; var barY2:Number; matrix.createGradientBox(barWidthSplit, barHeight, 0, barX, barY); g.beginGradientFill(GradientType.LINEAR, colors, [ .39, .85], ratios, matrix); g.drawRect(barX, barY, barWidthSplit, barHeight); matrix.createGradientBox(barWidthSplit, barHeight, 0, barX + barWidthSplit, barY); g.beginGradientFill(GradientType.LINEAR, colors, [.85, 1.0], ratios, matrix); g.drawRect(barX + barWidthSplit, barY, barWidthSplit, barHeight); // Outer highlight barWidthSplit = barWidth / 3; barHeight = _barRect.height; barY = calcY(_barRect.y); barY2 = barY + barHeight - 1; matrix.createGradientBox(barWidthSplit, barHeight, 0, barX, barY); g.beginGradientFill(GradientType.LINEAR, colors, [ .05, .15], ratios, matrix); g.drawRect(barX, barY, barWidthSplit, 1); g.drawRect(barX, barY2, barWidthSplit, 1); matrix.createGradientBox(barWidthSplit, barHeight, 0, barX + barWidthSplit, barY); g.beginGradientFill(GradientType.LINEAR, colors, [ .15, .25], ratios, matrix); g.drawRect(barX + barWidthSplit, barY, barWidthSplit, 1); g.drawRect(barX + barWidthSplit, barY2, barWidthSplit, 1); matrix.createGradientBox(barWidthSplit, barHeight, 0, barX + barWidthSplit * 2, barY); g.beginGradientFill(GradientType.LINEAR, colors, [ .25, .1], ratios, matrix); g.drawRect(barX + barWidthSplit * 2, barY, barWidthSplit, 1); g.drawRect(barX + barWidthSplit * 2, barY2, barWidthSplit, 1); // Inner highlight barWidthSplit = barWidth / 3; barHeight = _barRect.height; barY = calcY(_barRect.y) + 1; barY2 = calcY(_barRect.y) + barHeight - 2; matrix.createGradientBox(barWidthSplit, barHeight, 0, barX, barY); g.beginGradientFill(GradientType.LINEAR, colors, [ .15, .30], ratios, matrix); g.drawRect(barX, barY, barWidthSplit, 1); g.drawRect(barX, barY2, barWidthSplit, 1); matrix.createGradientBox(barWidthSplit, barHeight, 0, barX + barWidthSplit, barY); g.beginGradientFill(GradientType.LINEAR, colors, [ .30, .40], ratios, matrix); g.drawRect(barX + barWidthSplit, barY, barWidthSplit, 1); g.drawRect(barX + barWidthSplit, barY2, barWidthSplit, 1); matrix.createGradientBox(barWidthSplit, barHeight, 0, barX + barWidthSplit * 2, barY); g.beginGradientFill(GradientType.LINEAR, colors, [ .40, .25], ratios, matrix); g.drawRect(barX + barWidthSplit * 2, barY, barWidthSplit, 1); g.drawRect(barX + barWidthSplit * 2, barY2, barWidthSplit, 1); } /** * Updates the display of the download progress bar * with the current download information. * A typical implementation divides the loaded value by the total value * and displays a percentage. * If you do not implement this method, you should create * a progress bar that displays an animation to indicate to the user * that a download is occurring. * *

The setProgress() method is only called * if the application is being downloaded from a remote server * and the application is not in the browser cache.

* * @param completed Number of bytes of the application SWF file * that have been downloaded. * * @param total Size of the application SWF file in bytes. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function setProgress(completed:Number, total:Number):void { if (!isNaN(completed) && !isNaN(total) && completed >= 0 && total > 0) { _value = Number(completed); _maximum = Number(total); draw(); } } /** * Returns the percentage value of the application loaded. * * @param loaded Number of bytes of the application SWF file * that have been downloaded. * * @param total Size of the application SWF file in bytes. * * @return The percentage value of the loaded application. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function getPercentLoaded(loaded:Number, total:Number):Number { var perc:Number; if (loaded == 0 || total == 0 || isNaN(total) || isNaN(loaded)) return 0; else perc = 100 * loaded/total; if (isNaN(perc) || perc <= 0) return 0; else if (perc > 99) return 99; else return Math.round(perc); } /** * @private * Make the display class visible. */ private function show():void { _showingDisplay = true; calcScale(); draw(); _displayTime = getTimer(); // Time when the display is shown. } /** * @private */ private function hide():void { } /** * @private */ private function calcX(base:Number):Number { return base + _xOffset; } /** * @private */ private function calcY(base:Number):Number { return base + _yOffset; } /** * @private * Figure out the scale for the display class based on the stage size. * Then creates the children subcomponents. */ private function calcScale():void { if (stageWidth < 160 || stageHeight < 120) { scaleX = 1.0; scaleY = 1.0; } else if (stageWidth < 240 || stageHeight < 150) { // Scale to appropriate size createChildren(); var scale:Number = Math.min(stageWidth / 240.0, stageHeight / 150.0); scaleX = scale; scaleY = scale; } else { createChildren(); } } /** * Defines the algorithm for determining whether to show * the download progress bar while in the download phase. * * @param elapsedTime number of milliseconds that have elapsed * since the start of the download phase. * * @param event The ProgressEvent object that contains * the bytesLoaded and bytesTotal properties. * * @return If the return value is true, then show the * download progress bar. * The default behavior is to show the download progress bar * if more than 700 milliseconds have elapsed * and if Flex has downloaded less than half of the bytes of the SWF file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function showDisplayForDownloading(elapsedTime:int, event:ProgressEvent):Boolean { return elapsedTime > 700 && event.bytesLoaded < event.bytesTotal / 2; } /** * Defines the algorithm for determining whether to show the download progress bar * while in the initialization phase, assuming that the display * is not currently visible. * * @param elapsedTime number of milliseconds that have elapsed * since the start of the download phase. * * @param count number of times that the initProgress event * has been received from the application. * * @return If true, then show the download progress bar. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function showDisplayForInit(elapsedTime:int, count:int):Boolean { return elapsedTime > 300 && count == 2; } /** * @private */ private function loadBackgroundImage(classOrString:Object):void { var cls:Class; // The ""as"" operator checks to see if classOrString // can be coerced to a Class if (classOrString && classOrString as Class) { // Load background image given a class pointer cls = Class(classOrString); initBackgroundImage(new cls()); } else if (classOrString && classOrString is String) { try { cls = Class(getDefinitionByName(String(classOrString))); } catch(e:Error) { // ignore } if (cls) { var newStyleObj:DisplayObject = new cls(); initBackgroundImage(newStyleObj); } else { // Loading the image is slightly different // than in Loader.loadContent()... is this on purpose? // Load background image from external URL var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener( Event.COMPLETE, loader_completeHandler); loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, loader_ioErrorHandler); var loaderContext:LoaderContext = new LoaderContext(); loaderContext.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain); loader.load(new URLRequest(String(classOrString)), loaderContext); } } } /** * @private */ private function initBackgroundImage(image:DisplayObject):void { addChildAt(image,0); var backgroundImageWidth:Number = image.width; var backgroundImageHeight:Number = image.height; // Scale according to backgroundSize var percentage:Number = calcBackgroundSize(); if (isNaN(percentage)) { var sX:Number = 1.0; var sY:Number = 1.0; } else { var scale:Number = percentage * 0.01; sX = scale * stageWidth / backgroundImageWidth; sY = scale * stageHeight / backgroundImageHeight; } image.scaleX = sX; image.scaleY = sY; // Center everything. // Use a scrollRect to position and clip the image. var offsetX:Number = Math.round(0.5 * (stageWidth - backgroundImageWidth * sX)); var offsetY:Number = Math.round(0.5 * (stageHeight - backgroundImageHeight * sY)); image.x = offsetX; image.y = offsetY; // Adjust alpha to match backgroundAlpha if (!isNaN(backgroundAlpha)) image.alpha = backgroundAlpha; } /** * @private */ private function calcBackgroundSize():Number { var percentage:Number = NaN; if (backgroundSize) { var index:int = backgroundSize.indexOf(""%""); if (index != -1) percentage = Number(backgroundSize.substr(0, index)); } return percentage; } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * Event listener for the ProgressEvent.PROGRESS event. * This implementation updates the progress bar * with the percentage of bytes downloaded. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function progressHandler(event:ProgressEvent):void { var loaded:uint = event.bytesLoaded; var total:uint = event.bytesTotal; var elapsedTime:int = getTimer() - _startTime; // Only show the Loading phase if it will appear for awhile. if (_showingDisplay || showDisplayForDownloading(elapsedTime, event)) { if (!_startedLoading) { show(); label = downloadingLabel; _startedLoading = true; } setProgress(event.bytesLoaded, event.bytesTotal); } } /** * Event listener for the Event.COMPLETE event. * The default implementation does nothing. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function completeHandler(event:Event):void { } /** * Event listener for the RSLEvent.RSL_PROGRESS event. * The default implementation does nothing. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function rslProgressHandler(event:RSLEvent):void { } /** * Event listener for the RSLEvent.RSL_COMPLETE event. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function rslCompleteHandler(event:RSLEvent):void { var word:String = ""library""; if (event.isResourceModule) word = ""module""; label = ""Loaded "" + word + "" "" + event.rslIndex + "" of "" + event.rslTotal; } /** * Event listener for the RSLEvent.RSL_ERROR event. * This event listner handles any errors detected when downloading an RSL. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function rslErrorHandler(event:RSLEvent):void { _preloader.removeEventListener(ProgressEvent.PROGRESS, progressHandler); _preloader.removeEventListener(Event.COMPLETE, completeHandler); _preloader.removeEventListener(RSLEvent.RSL_PROGRESS, rslProgressHandler); _preloader.removeEventListener(RSLEvent.RSL_COMPLETE, rslCompleteHandler); _preloader.removeEventListener(RSLEvent.RSL_ERROR, rslErrorHandler); _preloader.removeEventListener(FlexEvent.INIT_PROGRESS, initProgressHandler); _preloader.removeEventListener(FlexEvent.INIT_COMPLETE, initCompleteHandler); if (!_showingDisplay) { show(); _showingDisplay = true; } label = ""RSL Error "" + (event.rslIndex + 1) + "" of "" + event.rslTotal; var errorField:ErrorField = new ErrorField(this); errorField.show(event.errorText); } /** * @private * Helper function that dispatches the Complete event to the preloader. * * @param event The event object. */ private function timerHandler(event:Event = null):void { dispatchEvent(new Event(Event.COMPLETE)); } /** * Event listener for the FlexEvent.INIT_PROGRESS event. * This implementation updates the progress bar * each time the event is dispatched, and changes the text of the label. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function initProgressHandler(event:Event):void { var elapsedTime:int = getTimer() - _startTime; _initProgressCount++; if (!_showingDisplay && showDisplayForInit(elapsedTime, _initProgressCount)) { _displayStartCount = _initProgressCount; show(); } if (_showingDisplay) { if (!_startedInit) { // First init progress event. _startedInit = true; label = initializingLabel; } var loaded:Number = 100 * _initProgressCount / (initProgressTotal - _displayStartCount); setProgress(Math.min(loaded, 100), 100); } } /** * Event listener for the FlexEvent.INIT_COMPLETE event. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function initCompleteHandler(event:Event):void { var elapsedTime:int = getTimer() - _displayTime; if (_showingDisplay && elapsedTime < MINIMUM_DISPLAY_TIME) { var timer:Timer = new Timer(MINIMUM_DISPLAY_TIME - elapsedTime, 1); timer.addEventListener(TimerEvent.TIMER, timerHandler); timer.start(); } else { timerHandler(); } } /** * @private */ private function loader_completeHandler(event:Event):void { var target:DisplayObject = DisplayObject(LoaderInfo(event.target).loader); initBackgroundImage(target); } private function loader_ioErrorHandler(event:IOErrorEvent):void { // Swallow the error } } } import flash.display.DisplayObject; import flash.display.Sprite; import flash.text.TextField; import flash.text.TextFormat; import flash.system.Capabilities; import flash.text.TextFieldAutoSize; import flash.display.DisplayObjectContainer; import flash.display.Stage; import mx.preloaders.DownloadProgressBar; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * @private * * Area to display error messages to help debug startup problems. * */ class ErrorField extends Sprite { private var downloadProgressBar:DownloadProgressBar; private const MIN_WIDTH_INCHES:int = 2; // min width of error message in inches private const MAX_WIDTH_INCHES:int = 6; // max width of error message in inches private const TEXT_MARGIN_PX:int = 10; //---------------------------------- // labelFormat //---------------------------------- /** * The TextFormat object of the TextField component of the label. * This is a read-only property which you must override * if you need to change it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get labelFormat():TextFormat { var tf:TextFormat = new TextFormat(); tf.color = 0x000000; tf.font = ""Verdana""; tf.size = 10; return tf; } /** * @private * * @param - parent - parent of the error field. */ public function ErrorField(downloadProgressBar:DownloadProgressBar) { super(); this.downloadProgressBar = downloadProgressBar; } /** * Create and show the error message. * * @param errorText - text for error message. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function show(errorText:String):void { if (errorText == null || errorText.length == 0) return; var screenWidth:Number = downloadProgressBar.stageWidth; var screenHeight:Number = downloadProgressBar.stageHeight; // create the text field for the message and // add it to the parent. var textField:TextField = new TextField(); textField.autoSize = TextFieldAutoSize.LEFT; textField.multiline = true; textField.wordWrap = true; textField.background = true; textField.defaultTextFormat = labelFormat; textField.text = errorText; textField.width = Math.max(MIN_WIDTH_INCHES * Capabilities.screenDPI, screenWidth - (TEXT_MARGIN_PX * 2)); textField.width = Math.min(MAX_WIDTH_INCHES * Capabilities.screenDPI, textField.width); textField.y = Math.max(0, screenHeight - TEXT_MARGIN_PX - textField.height); // center field horizontally textField.x = (screenWidth - textField.width) / 2; downloadProgressBar.parent.addChild(this); this.addChild(textField); } } ",12456,True,2519.380820634116,median "parser grammar CiscoParser; import Cisco_common, Cisco_aaa, Cisco_acl, Cisco_bgp, Cisco_cable, Cisco_crypto, Cisco_callhome, Cisco_eigrp, Cisco_ignored, Cisco_interface, Cisco_isis, Cisco_line, Cisco_logging, Cisco_mpls, Cisco_nat, Cisco_ntp, Cisco_ospf, Cisco_pim, Cisco_qos, Cisco_rip, Cisco_routemap, Cisco_sla, Cisco_snmp, Cisco_static, Cisco_track, Cisco_vxlan, Cisco_zone; options { superClass = 'org.batfish.grammar.cisco.parsing.CiscoBaseParser'; tokenVocab = CiscoLexer; } address_aiimgp_stanza : ADDRESS null_rest_of_line ; address_family_multicast_stanza : ADDRESS_FAMILY ( IPV4 | IPV6 ) NEWLINE address_family_multicast_tail ; address_family_multicast_tail : ( ( MULTIPATH NEWLINE ) | ( INTERFACE ALL ENABLE NEWLINE ) | null_af_multicast_tail | interface_multicast_stanza | ip_pim_tail )* ; ags_null : NO? ( DESCRIPTION | ID ) null_rest_of_line ; aiimgp_stanza : address_aiimgp_stanza ; al_null : NO? ( HIDEKEYS | LOGGING | NOTIFY ) null_rest_of_line ; allow_iimgp_stanza : ALLOW null_rest_of_line aiimgp_stanza* ; allowed_ip : ( ( hostname = IP_ADDRESS mask = IP_ADDRESS ) | hostname = IPV6_ADDRESS ) iname = variable NEWLINE ; ap_null : NO? ( AP_BLACKLIST_TIME | ENET_LINK_PROFILE | FLUSH_R1_ON_NEW_R0 | GENERAL_PROFILE | GROUP | LLDP | MESH_CLUSTER_PROFILE | MESH_HT_SSID_PROFILE | MESH_RADIO_PROFILE | PROVISIONING_PROFILE | SPECTRUM | WIRED_AP_PROFILE | WIRED_PORT_PROFILE ) null_rest_of_line ; ap_regulatory_domain_profile : REGULATORY_DOMAIN_PROFILE null_rest_of_line ( aprdp_null )* ; ap_system_profile : SYSTEM_PROFILE null_rest_of_line ( apsp_null )* ; apg_null : NO? ( AP_SYSTEM_PROFILE | DOT11A_RADIO_PROFILE | DOT11G_RADIO_PROFILE | IDS_PROFILE | VIRTUAL_AP ) null_rest_of_line ; apn_null : NO? ( VIRTUAL_AP ) null_rest_of_line ; aprdp_null : NO? ( COUNTRY_CODE | VALID_11A_40MHZ_CHANNEL_PAIR | VALID_11A_80MHZ_CHANNEL_GROUP | VALID_11A_CHANNEL | VALID_11G_40MHZ_CHANNEL_PAIR | VALID_11G_CHANNEL ) null_rest_of_line ; apsp_null : NO? ( BKUP_LMS_IP | DNS_DOMAIN | LMS_IP | LMS_PREEMPTION ) null_rest_of_line ; archive_log : LOG null_rest_of_line ( al_null )* ; archive_null : NO? ( MAXIMUM | PATH | WRITE_MEMORY ) null_rest_of_line ; av_null : NO? ( CAPTURE | INTERFACE | MODE | SHUTDOWN | TIMESOURCE ) null_rest_of_line ; bfd_null : NO? ( TRAP ) null_rest_of_line ; bfd_template_null : NO? ( ECHO | INTERVAL ) null_rest_of_line ; cisco_configuration : NEWLINE? (sl += stanza)+ COLON? NEWLINE? EOF ; configure_maintenance : MAINTENANCE null_rest_of_line ( configure_maintenance_null | configure_maintenance_router )* ; configure_maintenance_null : NO? ( IP ) null_rest_of_line ; configure_maintenance_router : NO? ( ROUTER ) null_rest_of_line ( configure_maintenance_router_null )* ; configure_maintenance_router_null : NO? ( ISOLATE ) null_rest_of_line ; configure_null : NO? ( | SESSION | TERMINAL ) null_rest_of_line ; cops_listener : LISTENER ( copsl_access_list ) ; copsl_access_list : ACCESS_LIST name = variable_permissive NEWLINE ; cp_ip_access_group : ( IP | IPV6 ) ACCESS_GROUP name = variable ( VRF vrf = variable )? ( IN | OUT ) NEWLINE ; cp_ip_flow : IP FLOW MONITOR name = variable ( INPUT | OUTPUT ) NEWLINE ; cp_management_plane : MANAGEMENT_PLANE NEWLINE mgp_stanza* ; cp_null : NO? ( EXIT | SCALE_FACTOR ) null_rest_of_line ; cp_service_policy : SERVICE_POLICY ( INPUT | OUTPUT ) name = variable NEWLINE ; cps_null : NO? ( AUTO_CERT_ALLOW_ALL | AUTO_CERT_ALLOWED_ADDRS | AUTO_CERT_PROV ) null_rest_of_line ; cqg_null : NO? ( PRECEDENCE | QUEUE | RANDOM_DETECT_LABEL ) null_rest_of_line ; cmf_null : NO? ( ALIAS | CALL_FORWARD | DEFAULT_DESTINATION | DIALPLAN_PATTERN | IP | KEEPALIVE | LIMIT_DN | MAX_CONFERENCES | MAX_DN | MAX_EPHONES | SECONDARY_DIALTONE | TIME_FORMAT | TIME_ZONE | TRANSFER_SYSTEM | TRANSLATION_PROFILE ) null_rest_of_line ; ctlf_null : NO? ( RECORD_ENTRY | SHUTDOWN ) null_rest_of_line ; d11_null : NO? ( ACCOUNTING | AUTHENTICATION | GUEST_MODE | MAX_ASSOCIATIONS | MBSSID | VLAN ) null_rest_of_line ; daemon_null : NO? ( EXEC | SHUTDOWN ) null_rest_of_line ; dapr_null : NO? ( ACTION | USER_MESSAGE ) null_rest_of_line ; dapr_webvpn : WEBVPN NEWLINE ( daprw_null )* ; daprw_null : NO? ( ALWAYS_ON_VPN | SVC | URL_LIST ) null_rest_of_line ; del_stanza : DEL null_rest_of_line ; dhcp_null : NO? ( INTERFACE ) null_rest_of_line ; dhcp_profile : NO? PROFILE null_rest_of_line ( dhcp_profile_null )* ; dhcp_profile_null : NO? ( DEFAULT_ROUTER | DOMAIN_NAME | DNS_SERVER | HELPER_ADDRESS | LEASE | POOL | SUBNET_MASK ) null_rest_of_line ; dialer_group : GROUP null_rest_of_line ( dialer_group_null )* ; dialer_group_null : NO? ( DIAL_STRING | INIT_STRING ) null_rest_of_line ; dialer_null : NO? ( WATCH_LIST ) null_rest_of_line ; domain_lookup : LOOKUP ( SOURCE_INTERFACE iname = interface_name | DISABLE ) NEWLINE ; domain_name : NAME hostname = variable_hostname NEWLINE ; domain_name_server : NAME_SERVER hostname = variable_hostname NEWLINE ; dspf_null : NO? ( ASSOCIATE | DESCRIPTION | CODEC | MAXIMUM | SHUTDOWN ) null_rest_of_line ; ednt_null : NO? ( CALL_FORWARD ) null_rest_of_line ; eh_null : NO? ( ACTION | ASYNCHRONOUS | DELAY | TRIGGER ) null_rest_of_line ; enable_null : ( ENCRYPTED_PASSWORD | READ_ONLY_PASSWORD | SUPER_USER_PASSWORD | TELNET ) null_rest_of_line ; enable_password : PASSWORD (LEVEL level = dec)? ( ep_plaintext | ep_sha512 // Do not reorder ep_cisco_encryption | ep_cisco_encryption ) NEWLINE ; enable_secret : SECRET ( ( dec pass = variable_secret ) | double_quoted_string ) NEWLINE ; ep_cisco_encryption : (type = dec)? (pass = variable_secret) (LEVEL level = dec)? (PBKDF2 | ENCRYPTED)? ; ep_plaintext : pass = variable ; ep_sha512 : (sha512pass = SHA512_PASSWORD) (seed = PASSWORD_SEED)? ; event_null : NO? ( ACTION | EVENT | SET ) null_rest_of_line ; flow_null : NO? ( CACHE | COLLECT | DESCRIPTION | DESTINATION | EXPORT_PROTOCOL | EXPORTER | MATCH | OPTION | RECORD | SOURCE | STATISTICS | TRANSPORT ) null_rest_of_line ; flow_version : NO? VERSION null_rest_of_line ( flowv_null )* ; flowv_null : NO? ( OPTIONS | TEMPLATE ) null_rest_of_line ; gae_null : NO? ( SMTP_SERVER ) null_rest_of_line ; gk_null : NO? ( GW_TYPE_PREFIX | LRQ | SHUTDOWN | ZONE ) null_rest_of_line ; gpsec_null : NO? ( AGE | DELETE_DYNAMIC_LEARN ) null_rest_of_line ; hardware_null : NO? ( IFACL | QOS | RBACL | SPAN | VACL ) null_rest_of_line ; ids_ap_classification_rule : AP_CLASSIFICATION_RULE double_quoted_string NEWLINE ( ids_ap_classification_rule_null )* ; ids_ap_classification_rule_null : NO? ( CONF_LEVEL_INCR | DISCOVERED_AP_CNT | SSID | SNR_MAX | SNR_MIN ) null_rest_of_line ; ids_ap_rule_matching : AP_RULE_MATCHING NEWLINE ( ids_ap_rule_matching_null )* ; ids_ap_rule_matching_null : NO? ( RULE_NAME ) null_rest_of_line ; ids_dos_profile : DOS_PROFILE double_quoted_string NEWLINE ( ids_dos_profile_null )* ; ids_dos_profile_null : NO? ( DETECT_AP_FLOOD | DETECT_CHOPCHOP_ATTACK | DETECT_CLIENT_FLOOD | DETECT_CTS_RATE_ANOMALY | DETECT_EAP_RATE_ANOMALY | DETECT_HT_40MHZ_INTOLERANCE | DETECT_INVALID_ADDRESS_COMBINATION | DETECT_MALFORMED_ASSOCIATION_REQUEST | DETECT_MALFORMED_AUTH_FRAME | DETECT_MALFORMED_HTIE | DETECT_MALFORMED_LARGE_DURATION | DETECT_OVERFLOW_EAPOL_KEY | DETECT_OVERFLOW_IE | DETECT_RATE_ANOMALIES | DETECT_RTS_RATE_ANOMALY | DETECT_TKIP_REPLAY_ATTACK ) null_rest_of_line ; ids_general_profile : GENERAL_PROFILE double_quoted_string NEWLINE ( ids_general_profile_null )* ; ids_general_profile_null : NO? ( WIRED_CONTAINMENT | WIRELESS_CONTAINMENT ) null_rest_of_line ; ids_impersonation_profile : IMPERSONATION_PROFILE double_quoted_string NEWLINE ( ids_impersonation_profile_null )* ; ids_impersonation_profile_null : NO? ( DETECT_AP_IMPERSONATION | DETECT_BEACON_WRONG_CHANNEL | DETECT_HOTSPOTTER ) null_rest_of_line ; ids_null : NO? ( MANAGEMENT_PROFILE | RATE_THRESHOLDS_PROFILE | SIGNATURE_PROFILE | WMS_LOCAL_SYSTEM_PROFILE ) null_rest_of_line ; ids_profile : PROFILE double_quoted_string NEWLINE ( ids_profile_null )* ; ids_profile_null : NO? ( DOS_PROFILE | GENERAL_PROFILE | SIGNATURE_MATCHING_PROFILE | IMPERSONATION_PROFILE | UNAUTHORIZED_DEVICE_PROFILE ) null_rest_of_line ; ids_signature_matching_profile : SIGNATURE_MATCHING_PROFILE double_quoted_string NEWLINE ( ids_signature_matching_profile_null )* ; ids_signature_matching_profile_null : NO? ( SIGNATURE ) null_rest_of_line ; ids_unauthorized_device_profile : UNAUTHORIZED_DEVICE_PROFILE double_quoted_string NEWLINE ( ids_unauthorized_device_profile_null )* ; ids_unauthorized_device_profile_null : NO? ( DETECT_ADHOC_NETWORK | DETECT_BAD_WEP | DETECT_HT_GREENFIELD | DETECT_INVALID_MAC_OUI | DETECT_MISCONFIGURED_AP | DETECT_VALID_SSID_MISUSE | DETECT_WIRELESS_BRIDGE | DETECT_WIRELESS_HOSTED_NETWORK | PRIVACY | PROTECT_SSID | PROTECT_VALID_STA | REQUIRE_WPA | SUSPECT_ROGUE_CONF_LEVEL | VALID_AND_PROTECTED_SSID ) null_rest_of_line ; ids_wms_general_profile : WMS_GENERAL_PROFILE NEWLINE ( ids_wms_general_profile_null )* ; ids_wms_general_profile_null : NO? ( COLLECT_STATS ) null_rest_of_line ; ifmap_null : NO? ( ENABLE ) null_rest_of_line ; iimgp_stanza : allow_iimgp_stanza ; imgp_stanza : interface_imgp_stanza | null_imgp_stanza ; inband_mgp_stanza : ( INBAND | OUT_OF_BAND ) NEWLINE imgp_stanza* ; interface_imgp_stanza : INTERFACE null_rest_of_line iimgp_stanza* ; interface_multicast_stanza : INTERFACE interface_name NEWLINE interface_multicast_tail* ; interface_multicast_tail : ( BOUNDARY | BSR_BORDER | DISABLE | DR_PRIORITY | ENABLE | ROUTER ) null_rest_of_line ; ip_as_path_regex_mode_stanza : IP AS_PATH REGEX_MODE ( ASN | STRING ) NEWLINE ; ip_dhcp_null : ( EXCLUDED_ADDRESS | PACKET | SMART_RELAY | SNOOPING | USE ) null_rest_of_line ; ip_dhcp_pool : POOL name = variable NEWLINE ( ip_dhcp_pool_null )* ; ip_dhcp_pool_null : NO? ( AUTHORITATIVE | BOOTFILE | CLIENT_IDENTIFIER | CLIENT_NAME | DEFAULT_ROUTER | DNS_SERVER | DOMAIN_NAME | HARDWARE_ADDRESS | HOST | LEASE | NETWORK | NEXT_SERVER | OPTION ) null_rest_of_line ; ip_dhcp_relay : RELAY ( NEWLINE | ip_dhcp_relay_null | ip_dhcp_relay_server ) ; ip_dhcp_relay_null : ( ALWAYS_ON | INFORMATION | OPTION | SOURCE_ADDRESS | SOURCE_INTERFACE | SUB_OPTION | USE_LINK_ADDRESS ) null_rest_of_line ; ip_dhcp_relay_server : SERVER ( ip = IP_ADDRESS | ip6 = IPV6_ADDRESS ) NEWLINE ; ip_domain_lookup : LOOKUP (VRF vrf = variable)? (SOURCE_INTERFACE iname = interface_name)? NEWLINE ; ip_domain_name : NAME (VRF vrf = variable)? hostname = variable_hostname NEWLINE ; ip_domain_null : ( LIST ) null_rest_of_line ; ip_probe_null : NO? ( BURST_SIZE | FREQUENCY | MODE | RETRIES ) null_rest_of_line ; ip_route_stanza : ( IP | MANAGEMENT ) ROUTE ( VRF vrf = variable )? ip_route_tail ; ip_route_tail : ( ( address = IP_ADDRESS mask = IP_ADDRESS ) | prefix = IP_PREFIX ) ( nexthopip = IP_ADDRESS | nexthopprefix = IP_PREFIX | GLOBAL | nexthopint = interface_name_unstructured )* ( ( ( ADMIN_DIST | ADMIN_DISTANCE )? distance = dec ) | ( METRIC metric = dec ) | ( TAG tag = dec ) | perm = PERMANENT | ( TRACK track = track_number ) | ( NAME variable ) )* NEWLINE ; ip_ssh_null : ( AUTHENTICATION_RETRIES | CLIENT | LOGGING | MAXSTARTUPS | PORT | RSA | SERVER | ( NO SHUTDOWN ) | SOURCE_INTERFACE | TIME_OUT ) null_rest_of_line ; ip_ssh_pubkey_chain : PUBKEY_CHAIN NEWLINE ( ( KEY_HASH | QUIT | USERNAME ) null_rest_of_line )+ ; ip_ssh_version : VERSION version = dec NEWLINE ; ipc_association : ASSOCIATION null_rest_of_line ( ipca_null )* ; ipca_null : NO? ( ASSOC_RETRANSMIT | LOCAL_IP | LOCAL_PORT | PATH_RETRANSMIT | PROTOCOL | REMOTE_IP | REMOTE_PORT | RETRANSMIT_TIMEOUT | SHUTDOWN ) null_rest_of_line ; ipdg_address : ip = IP_ADDRESS NEWLINE ; ipdg_null : ( IMPORT ) null_rest_of_line ; l2_null : NO? ( BRIDGE_DOMAIN | MTU | NEIGHBOR | VPN ) null_rest_of_line ; l2tpc_null : NO? DEFAULT? ( AUTHENTICATION | COOKIE | HELLO | HIDDEN_LITERAL | HOSTNAME | PASSWORD | RECEIVE_WINDOW | RETRANSMIT | TIMEOUT ) null_rest_of_line ; l2vpn_bridge_group : BRIDGE GROUP name = variable NEWLINE ( lbg_bridge_domain )* ; l2vpn_logging : LOGGING NEWLINE ( ( BRIDGE_DOMAIN | PSEUDOWIRE | VFI ) NEWLINE )+ ; l2vpn_xconnect : XCONNECT GROUP variable NEWLINE ( l2vpn_xconnect_p2p )* ; l2vpn_xconnect_p2p : NO? P2P null_rest_of_line ( lxp_neighbor | lxp_null )* ; lbg_bridge_domain : BRIDGE_DOMAIN name = variable NEWLINE ( lbgbd_mac | lbgbd_null | lbgbd_vfi )* ; lbgbd_mac : NO? MAC null_rest_of_line ( lbgbdm_limit )* ; lbgbd_null : NO? ( INTERFACE | MTU | NEIGHBOR | ROUTED ) null_rest_of_line ; lbgbd_vfi : NO? VFI null_rest_of_line ( lbgbdv_null )* ; lbgbdm_limit : NO? LIMIT null_rest_of_line ( lbgbdml_null )* ; lbgbdml_null : NO? ( ACTION | MAXIMUM ) null_rest_of_line ; lbgbdv_null : NO? ( NEIGHBOR ) null_rest_of_line ; license_null : NO? ( CENTRALIZED_LICENSING_ENABLE ) null_rest_of_line ; lpts_null : NO? ( FLOW ) null_rest_of_line ; lxp_neighbor : NO? NEIGHBOR null_rest_of_line ( lxpn_l2tp | lxpn_null )* ; lxp_null : NO? ( INTERFACE | MONITOR_SESSION ) null_rest_of_line ; lxpn_null : NO? ( SOURCE ) null_rest_of_line ; lxpn_l2tp : NO? L2TP null_rest_of_line ( lxpnl_null )* ; lxpnl_null : NO? ( LOCAL | REMOTE ) null_rest_of_line ; map_class_null : NO? ( DIALER ) null_rest_of_line ; management_api : API HTTP_COMMANDS NEWLINE ( management_api_null | management_api_vrf )* ; management_api_null : NO? ( AUTHENTICATION | EXIT | IDLE_TIMEOUT | PROTOCOL | SHUTDOWN ) null_rest_of_line ; management_api_vrf : VRF name = variable NEWLINE ( management_api_vrf_null )* ; management_api_vrf_null : NO? ( SHUTDOWN ) null_rest_of_line ; management_console : CONSOLE NEWLINE ( management_console_null )* ; management_console_null : NO? ( IDLE_TIMEOUT ) null_rest_of_line ; management_egress_interface_selection : MANAGEMENT EGRESS_INTERFACE_SELECTION NEWLINE ( management_egress_interface_selection_null )* ( EXIT NEWLINE )? ; management_egress_interface_selection_null : NO? ( APPLICATION ) null_rest_of_line ; management_ssh : SSH NEWLINE ( management_ssh_ip_access_group | management_ssh_null )* ; management_ssh_ip_access_group : IP ACCESS_GROUP name = variable ( IN | OUT ) NEWLINE ; management_ssh_null : NO? ( AUTHENTICATION | IDLE_TIMEOUT | SHUTDOWN ) null_rest_of_line ; management_telnet : TELNET NEWLINE ( management_telnet_ip_access_group | management_telnet_null )* ; management_telnet_ip_access_group : IP ACCESS_GROUP name = variable ( IN | OUT ) NEWLINE ; management_telnet_null : NO? ( IDLE_TIMEOUT | SHUTDOWN ) null_rest_of_line ; mgp_stanza : inband_mgp_stanza ; monitor_destination : NO? DESTINATION null_rest_of_line ( monitor_destination_null )* ; monitor_destination_null : NO? ( ERSPAN_ID | IP | MTU | ORIGIN ) null_rest_of_line ; monitor_null : NO? ( BUFFER_SIZE | DESCRIPTION | SHUTDOWN | SOURCE ) null_rest_of_line ; monitor_session_null : NO? ( DESTINATION ) null_rest_of_line ; mp_null : NO? ( CONNECT_SOURCE | DESCRIPTION | MESH_GROUP | REMOTE_AS | SHUTDOWN ) null_rest_of_line ; mt_null : NO? ( ADDRESS ) null_rest_of_line ; multicast_routing_stanza : MULTICAST_ROUTING NEWLINE ( address_family_multicast_stanza )* ; no_aaa_group_server_stanza : NO AAA GROUP SERVER null_rest_of_line ; no_ip_access_list_stanza : NO IP ACCESS_LIST null_rest_of_line ; null_af_multicast_tail : NSF NEWLINE ; vrfd_af_export : EXPORT ( vrfd_af_export_nonvpn | vrfd_af_export_vpn ) ; vrfd_af_export_nonvpn : (IPV4 | IPV6) (MULTICAST | UNICAST) prefix_limit=dec? MAP name = variable NEWLINE ; vrfd_af_export_vpn : MAP name = variable NEWLINE ; vrfd_af_import : IMPORT vrfd_af_import_map ; vrfd_af_import_map : MAP name = variable NEWLINE ; vrfd_af_route_target : ROUTE_TARGET type = both_export_import rt = route_target NEWLINE ; vrfd_af_null : NO? ( MAXIMUM | MDT ) null_rest_of_line ; null_imgp_stanza : NO? ( VRF ) null_rest_of_line ; nv_satellite : NO? ( SATELLITE ) null_rest_of_line ( nvs_null )* ; nvs_null : NO? ( DESCRIPTION | IP | SERIAL_NUMBER | TYPE ) null_rest_of_line ; of_null : NO? ( BIND | CONTROLLER | DEFAULT_ACTION | DESCRIPTION | ENABLE ) null_rest_of_line ; peer_sa_filter : SA_FILTER ( IN | OUT ) ( LIST | RP_LIST ) name = variable NEWLINE ; peer_stanza : PEER IP_ADDRESS NEWLINE ( mp_null | peer_sa_filter )* ; phone_proxy_null : NO? ( CIPC | CTL_FILE | DISABLE | MEDIA_TERMINATION | PROXY_SERVER | TFTP_SERVER | TLS_PROXY ) null_rest_of_line ; qm_length : LENGTH null_rest_of_line ; qm_streaming : STREAMING NEWLINE ( qms_null )* ; qms_null : NO? ( MAX_CONNECTIONS | SHUTDOWN ) null_rest_of_line ; redundancy_linecard_group : LINECARD_GROUP null_rest_of_line ( rlcg_null )* ; redundancy_main_cpu : MAIN_CPU null_rest_of_line ( redundancy_main_cpu_null )* ; redundancy_main_cpu_null : NO? ( AUTO_SYNC ) null_rest_of_line ; redundancy_null : NO? ( KEEPALIVE_ENABLE | MODE | NOTIFICATION_TIMER | PROTOCOL | SCHEME ) null_rest_of_line ; rf_arm_profile : ARM_PROFILE double_quoted_string NEWLINE ( rf_arm_profile_null )* ; rf_arm_profile_null : NO? ( ASSIGNMENT | BACKOFF_TIME | ERROR_RATE_THRESHOLD | FREE_CHANNEL_INDEX | IDEAL_COVERAGE_INDEX | MAX_TX_POWER | MIN_TX_POWER | ROGUE_AP_AWARE | SCANNING ) null_rest_of_line ; rf_null : NO? ( AM_SCAN_PROFILE | ARM_RF_DOMAIN_PROFILE | EVENT_THRESHOLDS_PROFILE | OPTIMIZATION_PROFILE ) null_rest_of_line ; rf_dot11a_radio_profile : DOT11A_RADIO_PROFILE double_quoted_string NEWLINE ( rf_dot11a_radio_profile_null )* ; rf_dot11a_radio_profile_null : NO? ( ARM_PROFILE | MODE | SPECTRUM_LOAD_BALANCING | SPECTRUM_MONITORING ) null_rest_of_line ; rf_dot11g_radio_profile : DOT11G_RADIO_PROFILE double_quoted_string NEWLINE ( rf_dot11g_radio_profile_null )* ; rf_dot11g_radio_profile_null : NO? ( ARM_PROFILE | MODE | SPECTRUM_LOAD_BALANCING | SPECTRUM_MONITORING ) null_rest_of_line ; rlcg_null : NO? ( MEMBER | MODE | REVERTIVE | RF_SWITCH ) null_rest_of_line ; rmc_null : NO? ( MAXIMUM ) null_rest_of_line ; role_null : NO? ( DESCRIPTION | RULE ) null_rest_of_line ; route_tail : iface = variable destination = IP_ADDRESS mask = IP_ADDRESS gateway = IP_ADDRESS ( ( ( distance = dec+ )? ( TRACK track = dec+ )? ) | ( TUNNELED ) ) NEWLINE ; router_multicast_stanza : IPV6? ROUTER ( IGMP | MLD | MSDP | PIM ) NEWLINE router_multicast_tail ; router_multicast_tail : ( address_family_multicast_stanza | ( INTERFACE ALL null_rest_of_line ) | interface_multicast_stanza | null_inner | peer_stanza | rmc_null )* ; s_access_line : ( linetype = HTTP | linetype = SSH | linetype = TELNET ) allowed_ip ; s_airgroupservice : AIRGROUPSERVICE null_rest_of_line ( ags_null )* ; s_ap : AP ( ap_null | ap_regulatory_domain_profile | ap_system_profile ) ; s_ap_group : AP_GROUP double_quoted_string NEWLINE ( apg_null )* ; s_ap_name : AP_NAME double_quoted_string NEWLINE ( apn_null )* ; s_application : APPLICATION NEWLINE SERVICE name = variable null_rest_of_line ( PARAM null_rest_of_line )* ( GLOBAL NEWLINE SERVICE name = variable null_rest_of_line )? ; s_application_var : APPLICATION name = variable NEWLINE ( av_null )* ; s_archive : ARCHIVE null_rest_of_line ( archive_log | archive_null )* ; s_authentication : AUTHENTICATION null_rest_of_line ; s_banner_ios : banner_header = ios_banner_header banner = ios_delimited_banner NEWLINE ; ios_banner_header : BANNER_IOS | BANNER_CONFIG_SAVE_IOS | BANNER_EXEC_IOS | BANNER_INCOMING_IOS | BANNER_LOGIN_IOS | BANNER_MOTD_IOS | BANNER_PROMPT_TIMEOUT_IOS | BANNER_SLIP_PPP_IOS ; s_bfd : BFD null_rest_of_line ( bfd_null )* ; s_bfd_template : BFD_TEMPLATE SINGLE_HOP name = variable_permissive NEWLINE bfd_template_null* ; s_cluster : NO? CLUSTER ( ENABLE | RUN ) null_rest_of_line ; s_call_manager_fallback : NO? CALL_MANAGER_FALLBACK NEWLINE ( cmf_null )+ ; s_configure : NO? CONFIGURE ( configure_maintenance | configure_null ) ; s_control_plane : CONTROL_PLANE ( SLOT dec )? NEWLINE s_control_plane_tail* ; s_control_plane_tail : cp_ip_access_group | cp_ip_flow | cp_management_plane | cp_null | cp_service_policy ; s_control_plane_security : CONTROL_PLANE_SECURITY NEWLINE ( cps_null )* ; s_cops : COPS ( cops_listener ) ; s_cos_queue_group : COS_QUEUE_GROUP null_rest_of_line ( cqg_null )* ; s_ctl_file : NO? CTL_FILE null_rest_of_line ( ctlf_null )* ; s_daemon : DAEMON null_rest_of_line ( daemon_null )* ; s_dhcp : NO? DHCP null_rest_of_line ( dhcp_null | dhcp_profile )* ; s_dialer : DIALER ( dialer_group | dialer_null ) ; s_dial_peer : DIAL_PEER null_rest_of_line ( NO? ( CALL_BLOCK | CODEC | DESCRIPTION | DESTINATION_PATTERN | DIRECT_INWARD_DIAL | DTMF_RELAY | FAX | FORWARD_DIGITS | INCOMING | ( IP ( QOS ) ) | MEDIA | PORT | PREFERENCE | PREFIX | PROGRESS_IND | SERVICE | SESSION | SHUTDOWN | SIGNALING | TRANSLATION_PROFILE | VAD | VOICE_CLASS ) null_rest_of_line )* ; s_domain : DOMAIN ( VRF vrf = variable )? ( domain_lookup | domain_name | domain_name_server ) ; s_domain_name : DOMAIN_NAME hostname = variable_hostname NEWLINE ; s_dot11 : DOT11 null_rest_of_line ( d11_null )* ; s_dspfarm : NO? DSPFARM null_rest_of_line ( dspf_null )* ; s_dynamic_access_policy_record : NO? DYNAMIC_ACCESS_POLICY_RECORD null_rest_of_line ( dapr_null | dapr_webvpn )* ; s_enable : ENABLE ( enable_null | enable_password | enable_secret ) ; s_ephone_dn_template : EPHONE_DN_TEMPLATE null_rest_of_line ( ednt_null )* ; s_event : NO? EVENT null_rest_of_line ( event_null )* ; s_event_handler : NO? EVENT_HANDLER null_rest_of_line ( eh_null )* ; s_event_monitor : EVENT_MONITOR NEWLINE ; s_flow : FLOW ( EXPORTER | EXPORTER_MAP | HARDWARE | MONITOR | MONITOR_MAP | PLATFORM | RECORD ) null_rest_of_line ( flow_null | flow_version )* ; s_flow_sampler_map : NO? FLOW_SAMPLER_MAP null_rest_of_line fsm_mode? ; fsm_mode : MODE RANDOM ONE_OUT_OF dec NEWLINE ; s_gatekeeper : GATEKEEPER NEWLINE ( gk_null )* ; s_global_port_security : GLOBAL_PORT_SECURITY NEWLINE ( gpsec_null )* ; s_guest_access_email : GUEST_ACCESS_EMAIL NEWLINE ( gae_null )* ; s_hardware : NO? HARDWARE null_rest_of_line ( hardware_null )* ; s_hostname : ( HOSTNAME | SWITCHNAME ) ( quoted_name = double_quoted_string | ( ( name_parts += ~NEWLINE )+ ) ) NEWLINE ; s_ids : IDS ( ids_ap_classification_rule | ids_ap_rule_matching | ids_dos_profile | ids_general_profile | ids_impersonation_profile | ids_null | ids_profile | ids_signature_matching_profile | ids_unauthorized_device_profile | ids_wms_general_profile ) ; s_ifmap : IFMAP null_rest_of_line ( ifmap_null )* ; s_interface_line : NO? INTERFACE BREAKOUT null_rest_of_line ; s_ip : IP ( ip_extcommunity_list | ip_local | ip_sla ) ; s_ip_default_gateway : NO? IP DEFAULT_GATEWAY ( ipdg_address | ipdg_null ) ; s_ip_dhcp : NO? ( IP | IPV6 ) DHCP ( ip_dhcp_null | ip_dhcp_pool | ip_dhcp_relay ) ; s_ip_domain : NO? IP DOMAIN ( ip_domain_lookup | ip_domain_name | ip_domain_null ) ; s_ip_domain_name : IP DOMAIN_NAME hostname = variable_hostname ( USE_VRF variable )? NEWLINE ; ip_local : LOCAL ipl_policy ; ipl_policy : POLICY ROUTE_MAP name = variable NEWLINE ; s_ip_name_server : IP NAME_SERVER ( VRF vrf = variable )? ( hostnames += ip_hostname )+ ( USE_VRF vrf = variable )? NEWLINE ; s_ip_nbar : IP NBAR CUSTOM null_rest_of_line ; s_ip_probe : IP PROBE null_rest_of_line ( ip_probe_null )* ; s_ip_route_mos : IP ROUTE IP_ADDRESS DEV interface_name NEWLINE ; s_ip_source_route : NO? IP SOURCE_ROUTE NEWLINE ; s_ip_ssh : NO? IP SSH ( ip_ssh_pubkey_chain | ip_ssh_version | ip_ssh_null ) ; s_ip_tacacs_source_interface : IP TACACS ( VRF vrf = variable )? SOURCE_INTERFACE iname = interface_name NEWLINE ; s_ip_wccp : NO? IP WCCP ( VRF vrf = variable )? ( wccp_id | wccp_null ) ; s_ipc : IPC null_rest_of_line ( ipc_association )* ; s_ipv6 : IPV6 ipv6_local ; ipv6_local : LOCAL ipv6l_policy ; ipv6l_policy : POLICY ROUTE_MAP name = variable NEWLINE ; s_l2 : NO? L2 null_rest_of_line ( l2_null )* ; s_l2tp_class : NO? L2TP_CLASS name = variable NEWLINE ( l2tpc_null )* ; s_l2vpn : NO? L2VPN null_rest_of_line ( l2vpn_bridge_group | l2vpn_logging | l2vpn_xconnect )* ; s_license : NO? LICENSE null_rest_of_line ( license_null )* ; s_lpts : NO? LPTS null_rest_of_line ( lpts_null )* ; s_management : MANAGEMENT ( management_api | management_console | management_egress_interface_selection | management_ssh | management_telnet ) ; s_map_class : NO? MAP_CLASS null_rest_of_line ( map_class_null )* ; s_media_termination : NO? MEDIA_TERMINATION null_rest_of_line ( mt_null )* ; s_monitor : NO? MONITOR null_rest_of_line ( monitor_destination | monitor_null )* ; s_monitor_session : NO? MONITOR_SESSION null_rest_of_line ( monitor_session_null )* ; s_name : NAME variable variable null_rest_of_line ; s_no_access_list_extended : NO ACCESS_LIST ACL_NUM_EXTENDED NEWLINE ; s_no_access_list_standard : NO ACCESS_LIST ACL_NUM_STANDARD NEWLINE ; s_no_bfd : NO BFD null_rest_of_line ; s_no_enable : NO ENABLE PASSWORD (LEVEL level = dec)? NEWLINE ; s_nv : NO? NV NEWLINE ( nv_satellite )* ; s_openflow : NO? OPENFLOW null_rest_of_line ( of_null )* ; s_passwd : NO? PASSWD pass = variable ENCRYPTED? NEWLINE ; s_phone_proxy : NO? PHONE_PROXY null_rest_of_line ( phone_proxy_null )* ; s_privilege : NO? PRIVILEGE ( CLEAR | CMD | CONFIGURE | EXEC | INTERFACE | IPENACL | ROUTER | SHOW ) null_rest_of_line ; s_process_max_time : NO? PROCESS_MAX_TIME dec NEWLINE ; s_queue_monitor : QUEUE_MONITOR ( qm_length | qm_streaming ) ; s_radius_server : RADIUS SERVER name = variable NEWLINE ( ( ADDRESS | KEY | RETRANSMIT | TIMEOUT ) null_rest_of_line )+ ; s_redundancy : NO? REDUNDANCY null_rest_of_line ( redundancy_linecard_group | redundancy_main_cpu | redundancy_null )* ; s_rf : RF ( rf_arm_profile | rf_null | rf_dot11a_radio_profile | rf_dot11g_radio_profile ) ; s_role : NO? ROLE null_rest_of_line ( role_null )* ; s_route : ROUTE route_tail ; s_sccp : NO? SCCP null_rest_of_line ( sccp_null )* ; s_service : NO? SERVICE ( words += variable )+ NEWLINE ; s_service_policy_global : SERVICE_POLICY name = variable GLOBAL NEWLINE ; s_sip_ua : SIP_UA NEWLINE ( sip_ua_null )* ; s_sntp : SNTP sntp_server ; s_spanning_tree : NO? SPANNING_TREE ( spanning_tree_mst | spanning_tree_portfast | spanning_tree_pseudo_information | spanning_tree_null | NEWLINE ) ; s_ssh : SSH ( ssh_access_group | ssh_client | ssh_null | ssh_server | ssh_timeout ) ; s_statistics : NO? STATISTICS null_rest_of_line ( statistics_null )* ; s_stcapp : STCAPP null_rest_of_line ( ( CALL | CPTONE | FALLBACK_DN | PICKUP | PORT | PREFIX ) null_rest_of_line )* ; s_switchport : SWITCHPORT DEFAULT MODE ( ACCESS | ROUTED ) NEWLINE ; s_system : NO? SYSTEM ( system_default | system_null | system_qos ) s_system_inner* ; s_system_inner : s_system_service_policy ; s_system_service_policy : SERVICE_POLICY TYPE QUEUING (INPUT | OUTPUT) policy_map = variable NEWLINE ; s_tacacs : TACACS ( t_null | t_server | t_source_interface ) ; s_tacacs_server : NO? TACACS_SERVER ( ts_common | ts_host | ( ts_host ts_common* ) ) ; s_tap : NO? TAP null_rest_of_line ( tap_null )* ; s_telephony_service : TELEPHONY_SERVICE null_rest_of_line ( telephony_service_null )* ; s_template : TEMPLATE null_rest_of_line ( template_null )* ; s_time_range : TIME_RANGE name = variable PERIODIC? NEWLINE ( tr_null )* ; s_tunnel_group : NO? TUNNEL_GROUP null_rest_of_line ( tg_null )* ; s_user_role : USER_ROLE name = variable_permissive NEWLINE ( ur_access_list | ur_null )* ; s_username : USERNAME ( quoted_user = double_quoted_string | user = variable ) ( ( u+ NEWLINE ) | ( NEWLINE ( u NEWLINE )* ) ) ; s_username_attributes : USERNAME user = variable ATTRIBUTES NEWLINE ( ua_null )* ; s_vlan_cisco : NO? VLAN ( ACCESS_MAP | ( variable_vlan? dec ) ) null_rest_of_line ( vlan_vn_segment | vlan_null )* ; s_vlan_internal_cisco : NO? VLAN INTERNAL ALLOCATION POLICY (ASCENDING | DESCENDING) NEWLINE ; s_vlan_name : VLAN_NAME name = variable_permissive NEWLINE ; s_voice : NO? VOICE ( voice_class | voice_null | voice_service | voice_translation_profile | voice_translation_rule ) ; s_voice_card : NO? VOICE_CARD null_rest_of_line ( vc_null )* ; s_voice_port : NO? VOICE_PORT null_rest_of_line ( vp_null )* ; s_vpc : NO? VPC null_rest_of_line ( vpc_null )* ; s_vpdn_group : NO? VPDN_GROUP null_rest_of_line ( vpdng_accept_dialin | vpdng_null )* ; s_vpn : NO? VPN null_rest_of_line ( vpn_null )* ; s_vpn_dialer : VPN_DIALER name = variable NEWLINE ( vpn_dialer_null )* ; // a way to define a VRF on IOS s_vrf_definition : // DEFINITION is for IOS VRF DEFINITION? name = variable NEWLINE ( vrfd_address_family | vrfd_description | vrfd_no | vrfd_null | vrfd_rd | vrfd_route_target )* ( EXIT_VRF NEWLINE )? ; s_web_server : WEB_SERVER PROFILE NEWLINE ( web_server_null )* ; s_webvpn : NO? WEBVPN null_rest_of_line ( webvpn_null )* ; s_wlan : WLAN ( wlan_null | wlan_ssid_profile | wlan_virtual_ap ) ; s_wsma : WSMA null_rest_of_line ( wsma_null )* ; s_xconnect_logging : NO? XCONNECT LOGGING null_rest_of_line ; sccp_null : NO? ( ASSOCIATE | BIND | DESCRIPTION | SWITCHBACK ) null_rest_of_line ; sd_null : ( DCE_MODE | INTERFACE | LINK_FAIL ) null_rest_of_line ; sd_switchport : SWITCHPORT ( sd_switchport_blank | sd_switchport_null | sd_switchport_shutdown ) ; sd_switchport_blank : NEWLINE ; sd_switchport_null : ( FABRICPATH | MONITOR ) null_rest_of_line ; sd_switchport_shutdown : SHUTDOWN NEWLINE ; sip_ua_null : NO? ( CONNECTION_REUSE | RETRY | SET | SIP_SERVER | TIMERS ) null_rest_of_line ; sntp_server : SERVER hostname = variable ( VERSION version = dec )? NEWLINE ; spanning_tree_mst : MST null_rest_of_line spanning_tree_mst_null* ; spanning_tree_mst_null : NO? ( INSTANCE | NAME | REVISION ) null_rest_of_line ; spanning_tree_portfast : PORTFAST ( bpdufilter = BPDUFILTER | bpduguard = BPDUGUARD | defaultLiteral = DEFAULT | edge = EDGE )* NEWLINE ; spanning_tree_pseudo_information : PSEUDO_INFORMATION NEWLINE ( spti_null )* ; spanning_tree_null : ( BACKBONEFAST | BPDUFILTER | BRIDGE | COST | DISPUTE | ETHERCHANNEL | EXTEND | FCOE | GUARD | LOGGING | LOOPGUARD | MODE | OPTIMIZE | PATHCOST | PORT | UPLINKFAST | VLAN ) null_rest_of_line ; spti_null : NO? ( MST ) null_rest_of_line ; srlg_interface_numeric_stanza : dec null_rest_of_line ; srlg_interface_stanza : INTERFACE null_rest_of_line srlg_interface_numeric_stanza* ; srlg_stanza : SRLG NEWLINE srlg_interface_stanza* ; ssh_access_group : ACCESS_GROUP IPV6? name = variable NEWLINE ; ssh_client : CLIENT null_rest_of_line ; ssh_null : ( IP_ADDRESS | KEY | KEY_EXCHANGE | LOGIN_ATTEMPTS | MGMT_AUTH | STRICTHOSTKEYCHECK | VERSION ) null_rest_of_line ; ssh_server : SERVER ( ( IPV4 ACCESS_LIST acl = variable ) | ( IPV6 ACCESS_LIST acl6 = variable ) | LOGGING | ( SESSION_LIMIT limit = dec ) | V2 | ( VRF vrf = variable ) )* NEWLINE ; ssh_timeout : TIMEOUT dec NEWLINE ; stanza : appletalk_access_list_stanza | del_stanza | extended_access_list_stanza | extended_ipv6_access_list_stanza | ip_as_path_access_list_stanza | ip_as_path_regex_mode_stanza | ip_community_list_expanded_stanza | ip_community_list_standard_stanza | ip_prefix_list_stanza | ip_route_stanza | ipv6_prefix_list_stanza | ipx_sap_access_list_stanza | multicast_routing_stanza | no_aaa_group_server_stanza | no_ip_access_list_stanza | no_ip_prefix_list_stanza | no_route_map_stanza | protocol_type_code_access_list_stanza | route_map_stanza | router_bgp_stanza | router_isis_stanza | router_multicast_stanza | rsvp_stanza | s_aaa | s_access_line | s_airgroupservice | s_ap | s_ap_group | s_ap_name | s_application | s_application_var | s_archive | s_arp_access_list_extended | s_authentication | s_banner_ios | s_bfd | s_bfd_template | s_cable | s_call_home | s_callhome | s_call_manager_fallback | s_class_map | s_class_map_ios | s_cluster | s_configure | s_control_plane | s_control_plane_security | s_controller | s_cops | s_cos_queue_group | s_crypto | s_ctl_file | s_daemon | s_depi_class | s_depi_tunnel | s_dhcp | s_dialer | s_dial_peer | s_domain | s_domain_name | s_dot11 | s_dspfarm | s_dynamic_access_policy_record | s_enable | s_ephone_dn_template | s_ethernet_services | s_event | s_event_handler | s_event_monitor | s_flow | s_flow_sampler_map | s_gatekeeper | s_global_port_security | s_guest_access_email | s_hardware | s_hostname | s_ids | s_ifmap | // do not move below s_interface s_interface_line | s_interface | s_ip | s_ip_access_list_eth | s_ip_default_gateway | s_ip_dhcp | s_ip_domain | s_ip_domain_name | s_ip_name_server | s_ip_nat | s_ip_nbar | s_ip_pim | s_ip_probe | s_ip_route_mos | s_ip_source_route | s_ip_ssh | s_ip_tacacs_source_interface | s_ip_wccp | s_ipc | s_ipv6 | s_ipv6_router_ospf | s_key | s_l2 | s_l2tp_class | s_l2vpn | s_license | s_line | s_logging | s_lpts | s_management | s_mac_access_list | s_mac_access_list_extended | s_map_class | s_media_termination | s_monitor | s_monitor_session | s_mpls_label_range | s_mpls_ldp | s_mpls_traffic_eng | s_name | s_netdestination | s_netdestination6 | s_netservice | s_no | s_no_access_list_extended | s_no_access_list_standard | s_no_bfd | s_no_enable | s_ntp | s_null | s_nv | s_object | s_object_group | s_openflow | s_passwd | s_phone_proxy | s_policy_map | s_policy_map_ios | s_privilege | s_process_max_time | s_qos_mapping | s_queue_monitor | s_radius_server | s_redundancy | s_rf | s_role | s_route | s_router_eigrp | s_router_ospf | s_router_ospfv3 | s_router_rip | s_router_static | s_sccp | s_service | s_service_policy_global | s_service_template | s_sip_ua | s_snmp_server | s_sntp | s_spanning_tree | s_ssh | s_statistics | s_stcapp | s_switchport | s_system | s_table_map | s_tacacs | s_tacacs_server | s_tap | s_telephony_service | s_template | s_time_range | s_track | s_tunnel_group | s_user_role | s_username | s_username_attributes | s_vlan_cisco | s_vlan_internal_cisco | s_vlan_name | s_voice | s_voice_card | s_voice_port | s_vpc | s_vpdn_group | s_vpn | s_vpn_dialer | s_vrf_definition | s_web_server | s_webvpn | s_wlan | s_wsma | s_xconnect_logging | s_zone | s_zone_pair | srlg_stanza | standard_access_list_stanza | standard_ipv6_access_list_stanza | switching_mode_stanza ; s_no : NO ( no_ip | no_track ) ; no_ip : IP ( no_ip_sla ) ; statistics_null : NO? ( EXTENDED_COUNTERS | TM_VOQ_COLLECTION ) null_rest_of_line ; switching_mode_stanza : SWITCHING_MODE null_rest_of_line ; system_default : DEFAULT ( sd_null | sd_switchport ) ; system_null : ( ADMIN_VDC | AUTO_UPGRADE | FABRIC | FABRIC_MODE | FLOWCONTROL | INTERFACE | JUMBOMTU | MODE | MODULE_TYPE | MTU | ROUTING | URPF | VLAN ) null_rest_of_line ; system_qos : QOS NEWLINE ( system_qos_null )* ; system_qos_null : NO? ( FEX | SERVICE_POLICY ) null_rest_of_line ; t_null : ( GROUP | HOST ) null_rest_of_line ; t_server : SERVER hostname = variable_hostname NEWLINE ( t_server_address | t_key | t_server_null )* ; t_server_address : ADDRESS ( ( IPV4 IP_ADDRESS ) | ( IPV6 IPV6_ADDRESS ) ) NEWLINE ; t_server_null : NO? ( SINGLE_CONNECTION | TIMEOUT ) null_rest_of_line ; t_key : KEY dec? variable_permissive NEWLINE ; t_source_interface : SOURCE_INTERFACE iname = interface_name ( VRF name = variable )? NEWLINE ; tap_null : NO? ( MODE ) null_rest_of_line ; telephony_service_null : NO? ( IP | MAX_CONFERENCES | MAX_EPHONES | SRST | TRANSFER_SYSTEM ) null_rest_of_line ; template_null : NO? ( ACCESS_SESSION | AUTHENTICATION | DOT1X | MAB | RADIUS_SERVER ) null_rest_of_line ; tg_null : NO? ( ACCOUNTING_SERVER_GROUP | ADDRESS_POOL | AUTHENTICATION | AUTHENTICATION_SERVER_GROUP | DEFAULT_GROUP_POLICY | GROUP_URL | IPV6_ADDRESS_POOL | ISAKMP ) null_rest_of_line ; tr_null : NO? ( WEEKDAY | WEEKEND ) null_rest_of_line ; ts_common : ts_null ; ts_host : HOST hostname = ( IP_ADDRESS | IPV6_ADDRESS ) null_rest_of_line t_key? ; ts_null : ( DEADTIME | DIRECTED_REQUEST | KEY | RETRANSMIT | TEST | TIMEOUT ) null_rest_of_line ; u : u_encrypted_password | u_nohangup | u_passphrase | u_password | u_privilege | u_role ; u_encrypted_password : ENCRYPTED_PASSWORD pass = variable_permissive ; u_nohangup : NOHANGUP ; u_passphrase : PASSPHRASE ( GRACETIME gracetime = dec | LIFETIME lifetime = dec | WARNTIME warntime = dec )* ; u_password : ( ( PASSWORD | SECRET ) up_cisco ) | ( NOPASSWORD ) ; u_privilege : PRIVILEGE privilege = variable ; u_role : ( GROUP | ROLE ) role = variable ; ua_null : ( GROUP_LOCK | VPN_GROUP_POLICY ) null_rest_of_line ; up_cisco : dec? up_cisco_tail ; up_cisco_tail : (pass = variable_secret) ( ENCRYPTED | MSCHAP | NT_ENCRYPTED | PBKDF2 )? ; ur_access_list : ACCESS_LIST SESSION name = variable_permissive NEWLINE ; ur_null : NO? ( CAPTIVE_PORTAL | MAX_SESSIONS | VLAN ) null_rest_of_line ; vc_null : NO? ( CODEC | DSP | DSPFARM | VOICE_SERVICE | WATCHDOG ) null_rest_of_line ; vlan_vn_segment : VN_SEGMENT vni = dec NEWLINE ; vlan_null : NO? ( ACTION | BACKUPCRF | BRIDGE | MATCH | MEDIA | MTU | MULTICAST | NAME | PARENT | PRIORITY | PRIVATE_VLAN | REMOTE_SPAN | ROUTER_INTERFACE | SHUTDOWN | SPANNING_TREE | STATE | STATISTICS | STP | TAGGED | TRUNK | TB_VLAN1 | TB_VLAN2 | UNTAGGED ) null_rest_of_line ; voice_class : CLASS ( voice_class_codec | voice_class_dpg | voice_class_e164 | voice_class_h323 | voice_class_server_group | voice_class_sip_profiles | voice_class_uri ) ; voice_class_codec : CODEC null_rest_of_line ( voice_class_codec_null )* ; voice_class_codec_null : NO? ( CODEC ) null_rest_of_line ; voice_class_dpg : DPG null_rest_of_line ( voice_class_dpg_null )* ; voice_class_dpg_null : NO? ( DESCRIPTION | DIAL_PEER ) null_rest_of_line ; voice_class_e164 : E164_PATTERN_MAP null_rest_of_line ( voice_class_e164_null )* ; voice_class_e164_null : NO? ( DESCRIPTION | E164 | URL ) null_rest_of_line ; voice_class_h323 : H323 null_rest_of_line ( voice_class_h323_null )* ; voice_class_h323_null : NO? ( CALL | H225 | TELEPHONY_SERVICE ) null_rest_of_line ; voice_class_server_group : SERVER_GROUP null_rest_of_line ( voice_class_server_group_null )* ; voice_class_server_group_null : NO? ( DESCRIPTION | IPV4 ) null_rest_of_line ; voice_class_sip_profiles : SIP_PROFILES null_rest_of_line ( voice_class_sip_profiles_null )* ; voice_class_sip_profiles_null : NO? ( REQUEST ) null_rest_of_line ; voice_class_uri : URI null_rest_of_line ( HOST null_rest_of_line ) ; voice_null : ( ALG_BASED_CAC | CALL | DIALPLAN_PROFILE | HUNT | IEC | LOGGING | REAL_TIME_CONFIG | RTCP_INACTIVITY | RTP | SIP | SIP_MIDCALL_REQ_TIMEOUT ) null_rest_of_line ; voice_service : SERVICE ( voice_service_voip ) ; voice_service_voip : VOIP NEWLINE ( voice_service_voip_h323 | voice_service_voip_ip_address_trusted_list | voice_service_voip_null | voice_service_voip_sip )* ; voice_service_voip_h323 : H323 NEWLINE ( voice_service_voip_h323_null )* ; voice_service_voip_h323_null : NO? ( CALL | H225 ) null_rest_of_line ; voice_service_voip_ip_address_trusted_list : IP ADDRESS TRUSTED LIST NEWLINE ( voice_service_voip_ip_address_trusted_list_null )* ; voice_service_voip_ip_address_trusted_list_null : NO? ( IPV4 ) null_rest_of_line ; voice_service_voip_null : NO? ( ADDRESS_HIDING | ALLOW_CONNECTIONS | FAX | H225 | MEDIA | MODE | MODEM | REDUNDANCY_GROUP | RTP_PORT | SHUTDOWN | SUPPLEMENTARY_SERVICE ) null_rest_of_line ; voice_service_voip_sip : SIP NEWLINE ( voice_service_voip_sip_null )* ; voice_service_voip_sip_null : NO? ( BIND | EARLY_OFFER | ERROR_PASSTHRU | G729 | HEADER_PASSING | LISTEN_PORT | MIDCALL_SIGNALING | SIP_PROFILES | TRANSPORT ) null_rest_of_line ; voice_translation_profile : TRANSLATION_PROFILE null_rest_of_line ( voice_translation_profile_null )* ; voice_translation_profile_null : NO? ( TRANSLATE ) null_rest_of_line ; voice_translation_rule : TRANSLATION_RULE null_rest_of_line ( voice_translation_rule_null )* ; voice_translation_rule_null : NO? ( RULE ) null_rest_of_line ; vp_null : NO? ( CALLER_ID | CONNECTION | CPTONE | DESCRIPTION | ECHO_CANCEL | SHUTDOWN | SIGNAL | TIMEOUTS | TIMING ) null_rest_of_line ; vpc_null : NO? ( AUTO_RECOVERY | DELAY | DUAL_ACTIVE | GRACEFUL | IP | PEER_CONFIG_CHECK_BYPASS | PEER_GATEWAY | PEER_KEEPALIVE | PEER_SWITCH | ROLE | SYSTEM_PRIORITY ) null_rest_of_line ; vpdng_accept_dialin : NO? ACCEPT_DIALIN null_rest_of_line ( vpdnga_null )* ; vpdng_null : NO? ( L2TP ) null_rest_of_line ; vpdnga_null : NO? ( PROTOCOL | VIRTUAL_TEMPLATE ) null_rest_of_line ; vpn_dialer_null : NO? ( IKE ) null_rest_of_line ; vpn_null : NO? ( CLUSTER | PARTICIPATE | PRIORITY | REDIRECT_FQDN ) null_rest_of_line ; vrfd_address_family : ADDRESS_FAMILY ( IPV4 | IPV6 ) ( MULTICAST | UNICAST )? ( MAX_ROUTE dec )? NEWLINE ( vrfd_af_export | vrfd_af_import | vrfd_af_null | vrfd_af_route_target )* ( EXIT_ADDRESS_FAMILY NEWLINE )? ; vrfd_description : description_line ; vrfd_no : NO vrfd_no_null ; vrfd_no_null : ( AUTO_IMPORT | IPV4 MULTICAST ) null_rest_of_line ; vrfd_null : AUTO_IMPORT null_rest_of_line ; vrfd_rd : RD (AUTO | rd = route_distinguisher) NEWLINE ; vrfd_route_target : ROUTE_TARGET type = both_export_import rt = route_target NEWLINE ; wccp_id : id = dec ( ( GROUP_LIST group_list = variable ) | ( MODE ( CLOSED | OPEN ) ) | ( PASSWORD dec? password = variable ) | ( REDIRECT_LIST redirect_list = variable ) | ( SERVICE_LIST service_list = variable ) )* NEWLINE ; wccp_null : ( CHECK | OUTBOUND_ACL_CHECK | SOURCE_INTERFACE | VERSION | WEB_CACHE ) null_rest_of_line ; web_server_null : NO? ( CAPTIVE_PORTAL_CERT | IDP_CERT | SESSION_TIMEOUT | SWITCH_CERT | WEB_HTTPS_PORT_443 | WEB_MAX_CLIENTS ) null_rest_of_line ; webvpn_null : NO? ( ANYCONNECT | ANYCONNECT_ESSENTIALS | CACHE | CSD | DISABLE | ENABLE | ERROR_RECOVERY | KEEPOUT | TUNNEL_GROUP_LIST ) null_rest_of_line ; wlan_null : NO? ( BCN_RPT_REQ_PROFILE | DOT11K_PROFILE | DOT11R_PROFILE | EDCA_PARAMETERS_PROFILE | HANDOVER_TRIGGER_PROFILE | HOTSPOT | HT_SSID_PROFILE | RRM_IE_PROFILE | TSM_REQ_PROFILE | VOIP_CAC_PROFILE ) null_rest_of_line ; wlan_ssid_profile : SSID_PROFILE double_quoted_string NEWLINE ( wlan_ssid_profile_null )* ; wlan_ssid_profile_null : NO? ( EAPOL_RATE_OPT | ESSID | HT_SSID_PROFILE | MAX_CLIENTS | MCAST_RATE_OPT | OPMODE | SSID_ENABLE | WMM ) null_rest_of_line ; wlan_virtual_ap : VIRTUAL_AP double_quoted_string NEWLINE ( wlan_virtual_ap_null )* ; wlan_virtual_ap_null : NO? ( AAA_PROFILE | AUTH_FAILURE_BLACKLIST_TIME | BAND_STEERING | BLACKLIST | BLACKLIST_TIME | BROADCAST_FILTER | DENY_INTER_USER_TRAFFIC | DYNAMIC_MCAST_OPTIMIZATION | DYNAMIC_MCAST_OPTIMIZATION_THRESH | SSID_PROFILE | VAP_ENABLE | VLAN ) null_rest_of_line ; wsma_null : NO? ( PROFILE | TRANSPORT ) null_rest_of_line ; ",16323,True,3886.864912389145,median "package com.ankamagames.dofus.logic.game.approach.frames { import by.blooddy.crypto.MD5; import com.ankamagames.berilia.Berilia; import com.ankamagames.berilia.managers.KernelEventsManager; import com.ankamagames.berilia.managers.UiModuleManager; import com.ankamagames.berilia.types.data.UiModule; import com.ankamagames.berilia.types.messages.AllModulesLoadedMessage; import com.ankamagames.berilia.types.shortcut.Shortcut; import com.ankamagames.dofus.BuildInfos; import com.ankamagames.dofus.Constants; import com.ankamagames.dofus.console.moduleLUA.ConsoleLUA; import com.ankamagames.dofus.console.moduleLogger.Console; import com.ankamagames.dofus.console.moduleLogger.ModuleDebugManager; import com.ankamagames.dofus.datacenter.servers.Server; import com.ankamagames.dofus.externalnotification.ExternalNotificationManager; import com.ankamagames.dofus.internalDatacenter.connection.BasicCharacterWrapper; import com.ankamagames.dofus.internalDatacenter.connection.CreationCharacterWrapper; import com.ankamagames.dofus.internalDatacenter.items.ItemWrapper; import com.ankamagames.dofus.kernel.Kernel; import com.ankamagames.dofus.kernel.net.ConnectionsHandler; import com.ankamagames.dofus.logic.common.frames.FeatureFrame; import com.ankamagames.dofus.logic.common.frames.LoadingModuleFrame; import com.ankamagames.dofus.logic.common.frames.MiscFrame; import com.ankamagames.dofus.logic.common.managers.FeatureManager; import com.ankamagames.dofus.logic.common.managers.PlayerManager; import com.ankamagames.dofus.logic.connection.frames.GameStartingFrame; import com.ankamagames.dofus.logic.connection.frames.ServerSelectionFrame; import com.ankamagames.dofus.logic.connection.managers.AuthentificationManager; import com.ankamagames.dofus.logic.game.approach.actions.CharacterCreationAction; import com.ankamagames.dofus.logic.game.approach.actions.CharacterDeletionAction; import com.ankamagames.dofus.logic.game.approach.actions.CharacterDeselectionAction; import com.ankamagames.dofus.logic.game.approach.actions.CharacterNameSuggestionRequestAction; import com.ankamagames.dofus.logic.game.approach.actions.CharacterRemodelSelectionAction; import com.ankamagames.dofus.logic.game.approach.actions.CharacterReplayRequestAction; import com.ankamagames.dofus.logic.game.approach.actions.CharacterSelectionAction; import com.ankamagames.dofus.logic.game.approach.actions.GiftAssignRequestAction; import com.ankamagames.dofus.logic.game.common.actions.CharacterAutoConnectAction; import com.ankamagames.dofus.logic.game.common.actions.chat.PopupWarningCloseRequestAction; import com.ankamagames.dofus.logic.game.common.frames.AdministrablePopupFrame; import com.ankamagames.dofus.logic.game.common.frames.AlignmentFrame; import com.ankamagames.dofus.logic.game.common.frames.AllianceFrame; import com.ankamagames.dofus.logic.game.common.frames.AveragePricesFrame; import com.ankamagames.dofus.logic.game.common.frames.CameraControlFrame; import com.ankamagames.dofus.logic.game.common.frames.ChatFrame; import com.ankamagames.dofus.logic.game.common.frames.CommonUiFrame; import com.ankamagames.dofus.logic.game.common.frames.ContextChangeFrame; import com.ankamagames.dofus.logic.game.common.frames.EmoticonFrame; import com.ankamagames.dofus.logic.game.common.frames.ExternalGameFrame; import com.ankamagames.dofus.logic.game.common.frames.ForgettableSpellsUiFrame; import com.ankamagames.dofus.logic.game.common.frames.HouseFrame; import com.ankamagames.dofus.logic.game.common.frames.IdolsFrame; import com.ankamagames.dofus.logic.game.common.frames.InventoryManagementFrame; import com.ankamagames.dofus.logic.game.common.frames.JobsFrame; import com.ankamagames.dofus.logic.game.common.frames.LivingObjectFrame; import com.ankamagames.dofus.logic.game.common.frames.MountFrame; import com.ankamagames.dofus.logic.game.common.frames.PartyManagementFrame; import com.ankamagames.dofus.logic.game.common.frames.PlayedCharacterUpdatesFrame; import com.ankamagames.dofus.logic.game.common.frames.ProgressionFrame; import com.ankamagames.dofus.logic.game.common.frames.ProtectPishingFrame; import com.ankamagames.dofus.logic.game.common.frames.QuestFrame; import com.ankamagames.dofus.logic.game.common.frames.ScreenCaptureFrame; import com.ankamagames.dofus.logic.game.common.frames.ServerTransferFrame; import com.ankamagames.dofus.logic.game.common.frames.SocialFrame; import com.ankamagames.dofus.logic.game.common.frames.SpellInventoryManagementFrame; import com.ankamagames.dofus.logic.game.common.frames.StackManagementFrame; import com.ankamagames.dofus.logic.game.common.frames.SynchronisationFrame; import com.ankamagames.dofus.logic.game.common.frames.TinselFrame; import com.ankamagames.dofus.logic.game.common.frames.WorldFrame; import com.ankamagames.dofus.logic.game.common.managers.DebtManager; import com.ankamagames.dofus.logic.game.common.managers.InactivityManager; import com.ankamagames.dofus.logic.game.common.managers.PlayedCharacterManager; import com.ankamagames.dofus.logic.game.common.managers.TimeManager; import com.ankamagames.dofus.logic.game.roleplay.frames.RoleplayIntroductionFrame; import com.ankamagames.dofus.logic.game.spin2.chat.ChatServiceManager; import com.ankamagames.dofus.logic.shield.SecureModeManager; import com.ankamagames.dofus.misc.interClient.InterClientManager; import com.ankamagames.dofus.misc.lists.HookList; import com.ankamagames.dofus.misc.stats.StatisticsManager; import com.ankamagames.dofus.misc.utils.errormanager.DofusErrorHandler; import com.ankamagames.dofus.network.ProtocolConstantsEnum; import com.ankamagames.dofus.network.enums.BuildTypeEnum; import com.ankamagames.dofus.network.enums.CharacterDeletionErrorEnum; import com.ankamagames.dofus.network.enums.CharacterRemodelingEnum; import com.ankamagames.dofus.network.enums.GameServerTypeEnum; import com.ankamagames.dofus.network.messages.authorized.ConsoleCommandsListMessage; import com.ankamagames.dofus.network.messages.game.approach.AccountCapabilitiesMessage; import com.ankamagames.dofus.network.messages.game.approach.AlreadyConnectedMessage; import com.ankamagames.dofus.network.messages.game.approach.AuthenticationTicketAcceptedMessage; import com.ankamagames.dofus.network.messages.game.approach.AuthenticationTicketMessage; import com.ankamagames.dofus.network.messages.game.approach.AuthenticationTicketRefusedMessage; import com.ankamagames.dofus.network.messages.game.approach.HelloGameMessage; import com.ankamagames.dofus.network.messages.game.basic.BasicTimeMessage; import com.ankamagames.dofus.network.messages.game.character.choice.BasicCharactersListMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterFirstSelectionMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterReplayWithRemodelRequestMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterSelectedErrorMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterSelectedForceMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterSelectedForceReadyMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterSelectedSuccessMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterSelectionMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterSelectionWithRemodelMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharactersListErrorMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharactersListMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharactersListRequestMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharactersListWithRemodelingMessage; import com.ankamagames.dofus.network.messages.game.character.creation.CharacterCanBeCreatedRequestMessage; import com.ankamagames.dofus.network.messages.game.character.creation.CharacterCanBeCreatedResultMessage; import com.ankamagames.dofus.network.messages.game.character.creation.CharacterCreationRequestMessage; import com.ankamagames.dofus.network.messages.game.character.creation.CharacterCreationResultMessage; import com.ankamagames.dofus.network.messages.game.character.creation.CharacterNameSuggestionFailureMessage; import com.ankamagames.dofus.network.messages.game.character.creation.CharacterNameSuggestionRequestMessage; import com.ankamagames.dofus.network.messages.game.character.creation.CharacterNameSuggestionSuccessMessage; import com.ankamagames.dofus.network.messages.game.character.deletion.CharacterDeletionErrorMessage; import com.ankamagames.dofus.network.messages.game.character.deletion.CharacterDeletionRequestMessage; import com.ankamagames.dofus.network.messages.game.character.replay.CharacterReplayRequestMessage; import com.ankamagames.dofus.network.messages.game.context.GameContextCreateRequestMessage; import com.ankamagames.dofus.network.messages.game.context.roleplay.fight.arena.GameRolePlayArenaSwitchToFightServerMessage; import com.ankamagames.dofus.network.messages.game.moderation.PopupWarningCloseRequestMessage; import com.ankamagames.dofus.network.messages.game.moderation.PopupWarningClosedMessage; import com.ankamagames.dofus.network.messages.game.startup.StartupActionFinishedMessage; import com.ankamagames.dofus.network.messages.game.startup.StartupActionsExecuteMessage; import com.ankamagames.dofus.network.messages.game.startup.StartupActionsListMessage; import com.ankamagames.dofus.network.messages.game.startup.StartupActionsObjetAttributionMessage; import com.ankamagames.dofus.network.messages.security.ClientKeyMessage; import com.ankamagames.dofus.network.types.game.character.choice.CharacterBaseInformations; import com.ankamagames.dofus.network.types.game.character.choice.CharacterHardcoreOrEpicInformations; import com.ankamagames.dofus.network.types.game.character.choice.CharacterToRemodelInformations; import com.ankamagames.dofus.network.types.game.character.choice.RemodelingInformation; import com.ankamagames.dofus.network.types.game.data.items.ObjectItemInformationWithQuantity; import com.ankamagames.dofus.network.types.game.startup.StartupActionAddObject; import com.ankamagames.dofus.scripts.api.CameraApi; import com.ankamagames.dofus.scripts.api.EntityApi; import com.ankamagames.dofus.scripts.api.ScriptSequenceApi; import com.ankamagames.dofus.types.data.ServerCommand; import com.ankamagames.dofus.uiApi.DataApi; import com.ankamagames.dofus.uiApi.SoundApi; import com.ankamagames.jerakine.data.I18n; import com.ankamagames.jerakine.data.XmlConfig; import com.ankamagames.jerakine.logger.Log; import com.ankamagames.jerakine.logger.LogLogger; import com.ankamagames.jerakine.logger.Logger; import com.ankamagames.jerakine.lua.LuaPlayer; import com.ankamagames.jerakine.managers.LangManager; import com.ankamagames.jerakine.managers.OptionManager; import com.ankamagames.jerakine.managers.StoreDataManager; import com.ankamagames.jerakine.messages.ConnectionResumedMessage; import com.ankamagames.jerakine.messages.Frame; import com.ankamagames.jerakine.messages.Message; import com.ankamagames.jerakine.network.messages.ServerConnectionFailedMessage; import com.ankamagames.jerakine.script.ScriptsManager; import com.ankamagames.jerakine.types.DataStoreType; import com.ankamagames.jerakine.types.enums.DataStoreEnum; import com.ankamagames.jerakine.types.enums.Priority; import com.ankamagames.jerakine.utils.benchmark.monitoring.FpsManager; import com.ankamagames.jerakine.utils.system.AirScanner; import flash.display.Loader; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.utils.getQualifiedClassName; import flash.utils.setTimeout; import scopart.raven.RavenClient; public class GameServerApproachFrame implements Frame { protected static const _log:Logger = Log.getLogger(getQualifiedClassName(GameServerApproachFrame)); private static var _changeLogLoader:Loader = new Loader(); public static var authenticationTicketAccepted:Boolean = false; private const LOADING_TIMEOUT:uint = 60000.0; private var _charactersList:Vector.; private var _charactersToRemodelList:Array; private var _kernel:KernelEventsManager; private var _gmaf:LoadingModuleFrame; private var _loadingStart:Number; private var _waitingMessages:Vector.; private var _cssmsg:CharacterSelectedSuccessMessage; private var _requestedCharacterId:Number; private var _requestedToRemodelCharacterId:Number; private var _waitingForListRefreshAfterDeletion:Boolean; private var _lc:LoaderContext; private var commonMod:Object; private var _giftList:Array; private var _charaListMinusDeadPeople:Array; private var _reconnectMsgSend:Boolean = false; private var _openCharsList:Boolean = true; public function GameServerApproachFrame() { this._charactersList = new Vector.(); this._charactersToRemodelList = []; this._kernel = KernelEventsManager.getInstance(); this._lc = new LoaderContext(false,ApplicationDomain.currentDomain); this.commonMod = UiModuleManager.getInstance().getModule(""Ankama_Common"").mainClass; this._giftList = []; this._charaListMinusDeadPeople = []; super(); } public function get priority() : int { return Priority.NORMAL; } public function get giftList() : Array { return this._giftList; } public function get charaListMinusDeadPeople() : Array { return this._charaListMinusDeadPeople; } public function get requestedCharaId() : Number { return this._requestedCharacterId; } public function set requestedCharaId(id:Number) : void { this._requestedCharacterId = id; } public function isCharacterWaitingForChange(id:Number) : Boolean { if(this._charactersToRemodelList[id]) { return true; } return false; } public function pushed() : Boolean { SecureModeManager.getInstance().checkMigrate(); AirScanner.allowByteCodeExecution(this._lc,true); Kernel.getWorker().addFrame(new MiscFrame()); Kernel.getWorker().addFrame(new FeatureFrame()); return true; } public function process(msg:Message) : Boolean { var perso:BasicCharacterWrapper = null; var characterId:Number = NaN; var isReplay:Boolean = false; var atmsg:AuthenticationTicketMessage = null; var atrmsg:AuthenticationTicketRefusedMessage = null; var scfMsg:ServerConnectionFailedMessage = null; var acmsg:AlreadyConnectedMessage = null; var clmsg:CharactersListMessage = null; var unusableCharacters:Vector. = null; var o:BasicCharacterWrapper = null; var unusable:Boolean = false; var server:Server = null; var bonusXp:int = 0; var mod:UiModule = null; var dst:DataStoreType = null; var isCharacterCreationDisplayForced:Boolean = false; var bclmsg:BasicCharactersListMessage = null; var b:BasicCharacterWrapper = null; var ccbcmsg:CharacterCanBeCreatedResultMessage = null; var accmsg:AccountCapabilitiesMessage = null; var cca:CharacterCreationAction = null; var ccmsg:CharacterCreationRequestMessage = null; var colors:Vector. = null; var ccrmsg:CharacterCreationResultMessage = null; var cda:CharacterDeletionAction = null; var cdrmsg:CharacterDeletionRequestMessage = null; var cdemsg:CharacterDeletionErrorMessage = null; var reason:String = null; var cnsra:CharacterNameSuggestionRequestAction = null; var cnsrmsg:CharacterNameSuggestionRequestMessage = null; var cnssmsg:CharacterNameSuggestionSuccessMessage = null; var cnsfmsg:CharacterNameSuggestionFailureMessage = null; var crsa:CharacterRemodelSelectionAction = null; var remodel:RemodelingInformation = null; var tempColorsArray:Vector. = null; var characterToConnect:BasicCharacterWrapper = null; var currentServer:Server = null; var bTutorial:Boolean = false; var cssmsg:CharacterSelectedSuccessMessage = null; var isRelease:* = false; var gccrmsg:GameContextCreateRequestMessage = null; var soundApi:SoundApi = null; var devMode:* = false; var now:Number = NaN; var delta:Number = NaN; var csemsg:CharacterSelectedErrorMessage = null; var btmsg:BasicTimeMessage = null; var date:Date = null; var salm:StartupActionsListMessage = null; var cclMsg:ConsoleCommandsListMessage = null; var stf:ServerTransferFrame = null; var pwcrmsg:PopupWarningCloseRequestMessage = null; var ccbcrm:CharacterCanBeCreatedRequestMessage = null; var clwrmsg:CharactersListWithRemodelingMessage = null; var ctri:CharacterToRemodelInformations = null; var chi:CharacterHardcoreOrEpicInformations = null; var featureManager:FeatureManager = null; var bonusXpFeatureActivated:Boolean = false; var cbi:CharacterBaseInformations = null; var cbi2:CharacterBaseInformations = null; var charToConnect:BasicCharacterWrapper = null; var saem:StartupActionsExecuteMessage = null; var ccbcrmsg:CharacterCanBeCreatedRequestMessage = null; var bChi:CharacterHardcoreOrEpicInformations = null; var bCbi:CharacterBaseInformations = null; var c:* = undefined; var colorIndex:* = undefined; var colorInteger:* = 0; var person2:Object = null; var crwrrmsg:CharacterReplayWithRemodelRequestMessage = null; var cswrmsg:CharacterSelectionWithRemodelMessage = null; var charToRemodel:Object = null; var indexedColors:Vector. = null; var char:CreationCharacterWrapper = null; var modificationModules:Array = null; var mandatoryModules:Array = null; var firstSelection:Boolean = false; var cfsmsg:CharacterFirstSelectionMessage = null; var crrmsg:CharacterReplayRequestMessage = null; var csmsg:CharacterSelectionMessage = null; var j:int = 0; var bchar:BasicCharacterWrapper = null; var flashKeyMsg:ClientKeyMessage = null; var fpsManagerState:uint = 0; var i:uint = 0; var luaPlayer:LuaPlayer = null; var tag:Object = null; var gift:StartupActionAddObject = null; var _items:Array = null; var item:ObjectItemInformationWithQuantity = null; var oj:Object = null; var iw:ItemWrapper = null; var gar:GiftAssignRequestAction = null; var sao:StartupActionsObjetAttributionMessage = null; var safm:StartupActionFinishedMessage = null; var indexToDelete:int = 0; var giftAction:Object = null; var cmdIndex:uint = 0; switch(true) { case msg is HelloGameMessage: ConnectionsHandler.confirmGameServerConnection(); authenticationTicketAccepted = false; atmsg = new AuthenticationTicketMessage(); atmsg.initAuthenticationTicketMessage(LangManager.getInstance().getEntry(""config.lang.current""),AuthentificationManager.getInstance().gameServerTicket); ConnectionsHandler.getConnection().send(atmsg); InactivityManager.getInstance().start(); this._kernel.processCallback(HookList.AuthenticationTicket); return true; case msg is AuthenticationTicketAcceptedMessage: setTimeout(this.requestCharactersList,500); authenticationTicketAccepted = true; this._kernel.processCallback(HookList.AuthenticationTicketAccepted); return true; case msg is AuthenticationTicketRefusedMessage: atrmsg = msg as AuthenticationTicketRefusedMessage; authenticationTicketAccepted = false; this._kernel.processCallback(HookList.AuthenticationTicketRefused); return true; case msg is ServerConnectionFailedMessage: scfMsg = ServerConnectionFailedMessage(msg); authenticationTicketAccepted = false; if(scfMsg.failedConnection == ConnectionsHandler.getConnection().getSubConnection(scfMsg)) { PlayerManager.getInstance().destroy(); this.commonMod.openPopup(I18n.getUiText(""ui.common.error""),I18n.getUiText(""ui.connexion.gameConnexionFailed""),[I18n.getUiText(""ui.common.ok"")],[this.onEscapePopup],this.onEscapePopup,this.onEscapePopup); KernelEventsManager.getInstance().processCallback(HookList.SelectedServerFailed); } return true; case msg is AlreadyConnectedMessage: acmsg = AlreadyConnectedMessage(msg); PlayerManager.getInstance().wasAlreadyConnected = true; KernelEventsManager.getInstance().processCallback(HookList.AlreadyConnected); return true; case msg is CharactersListMessage: clmsg = msg as CharactersListMessage; if(this._waitingForListRefreshAfterDeletion) { ccbcrm = new CharacterCanBeCreatedRequestMessage(); ccbcrm.initCharacterCanBeCreatedRequestMessage(); ConnectionsHandler.getConnection().send(ccbcrm); this._waitingForListRefreshAfterDeletion = false; } unusableCharacters = new Vector.(); if(msg is CharactersListWithRemodelingMessage) { clwrmsg = msg as CharactersListWithRemodelingMessage; for each(ctri in clwrmsg.charactersToRemodel) { this._charactersToRemodelList[ctri.id] = ctri; } } this._charactersList = new Vector.(); unusable = false; server = PlayerManager.getInstance().server; bonusXp = 1; if(server.gameTypeId == GameServerTypeEnum.SERVER_TYPE_HARDCORE || server.gameTypeId == GameServerTypeEnum.SERVER_TYPE_EPIC) { for each(chi in clmsg.characters) { if(unusableCharacters.indexOf(chi.id) != -1) { unusable = true; } if(chi.deathMaxLevel > chi.level) { bonusXp = 6; } else { bonusXp = 3; } o = BasicCharacterWrapper.create(chi.id,chi.name,chi.level,chi.entityLook,chi.breed,chi.sex,chi.deathState,chi.deathCount,chi.deathMaxLevel,bonusXp,unusable); this._charactersList.push(o); } } else { featureManager = FeatureManager.getInstance(); bonusXpFeatureActivated = !featureManager || featureManager.isFeatureWithKeywordEnabled(""character.xp.bonusForYoungerCharacters""); for each(cbi in clmsg.characters) { bonusXp = 1; if(unusableCharacters.indexOf(cbi.id) != -1) { unusable = true; } if(bonusXpFeatureActivated) { for each(cbi2 in clmsg.characters) { if(cbi2.id != cbi.id && cbi2.level > cbi.level && bonusXp < 4) { bonusXp++; } } } o = BasicCharacterWrapper.create(cbi.id,cbi.name,cbi.level,cbi.entityLook,cbi.breed,cbi.sex,0,0,0,bonusXp,unusable); this._charactersList.push(o); } } PlayerManager.getInstance().charactersList = this._charactersList; mod = UiModuleManager.getInstance().getModule(""Ankama_Connection""); dst = new DataStoreType(""AccountModule_"" + mod.id,true,DataStoreEnum.LOCATION_LOCAL,DataStoreEnum.BIND_ACCOUNT); isCharacterCreationDisplayForced = StoreDataManager.getInstance().getData(dst,""forceCharacterCreationDisplay""); if(this._charactersList.length && !isCharacterCreationDisplayForced) { this._openCharsList = true; charToConnect = this.getCharacterToConnect(); if(clmsg.hasStartupActions && !charToConnect) { saem = new StartupActionsExecuteMessage(); saem.initStartupActionsExecuteMessage(); ConnectionsHandler.getConnection().send(saem); this._openCharsList = false; } else if(charToConnect) { this.launchAutoConnect(charToConnect,server); } if(this._openCharsList) { if(!Berilia.getInstance().getUi(""characterSelection"")) { this._kernel.processCallback(HookList.CharacterSelectionStart,this._charactersList); } else { this._kernel.processCallback(HookList.CharactersListUpdated,this._charactersList); } } } else { this._kernel.processCallback(HookList.CharacterCreationStart,[[""create""],true]); this._kernel.processCallback(HookList.CharactersListUpdated,this._charactersList); } return true; case msg is BasicCharactersListMessage: bclmsg = msg as BasicCharactersListMessage; if(this._waitingForListRefreshAfterDeletion) { ccbcrmsg = new CharacterCanBeCreatedRequestMessage(); ccbcrmsg.initCharacterCanBeCreatedRequestMessage(); ConnectionsHandler.getConnection().send(ccbcrmsg); this._waitingForListRefreshAfterDeletion = false; } this._charactersList = new Vector.(); if(PlayerManager.getInstance().server.gameTypeId == GameServerTypeEnum.SERVER_TYPE_HARDCORE || PlayerManager.getInstance().server.gameTypeId == GameServerTypeEnum.SERVER_TYPE_EPIC) { for each(bChi in bclmsg.characters) { b = BasicCharacterWrapper.create(bChi.id,bChi.name,bChi.level,bChi.entityLook,bChi.breed,bChi.sex,bChi.deathState,bChi.deathCount,bChi.deathMaxLevel,1,false); this._charactersList.push(b); } } else { for each(bCbi in bclmsg.characters) { b = BasicCharacterWrapper.create(bCbi.id,bCbi.name,bCbi.level,bCbi.entityLook,bCbi.breed,bCbi.sex,0,0,0,1,false); this._charactersList.push(b); } } PlayerManager.getInstance().charactersList = this._charactersList; return true; case msg is CharactersListErrorMessage: this.commonMod.openPopup(I18n.getUiText(""ui.common.error""),I18n.getUiText(""ui.connexion.charactersListError""),[I18n.getUiText(""ui.common.ok"")]); return false; case msg is CharacterCanBeCreatedResultMessage: ccbcmsg = msg as CharacterCanBeCreatedResultMessage; PlayerManager.getInstance().canCreateNewCharacter = ccbcmsg.yesYouCan; KernelEventsManager.getInstance().processCallback(HookList.CharacterCanBeCreated); return true; case msg is AccountCapabilitiesMessage: accmsg = msg as AccountCapabilitiesMessage; this._kernel.processCallback(HookList.TutorielAvailable,accmsg.tutorialAvailable); this._kernel.processCallback(HookList.BreedsAvailable,accmsg.breedsAvailable,accmsg.breedsVisible); PlayerManager.getInstance().adminStatus = accmsg.status; PlayerManager.getInstance().canCreateNewCharacter = accmsg.canCreateNewCharacter; KernelEventsManager.getInstance().processCallback(HookList.CharacterCreationStart,[[""create""]]); return true; case msg is CharacterCreationAction: cca = msg as CharacterCreationAction; ccmsg = new CharacterCreationRequestMessage(); colors = new Vector.(); for each(c in cca.colors) { colors.push(c); } while(colors.length < ProtocolConstantsEnum.MAX_PLAYER_COLOR) { colors.push(-1); } ccmsg.initCharacterCreationRequestMessage(cca.name,cca.breed,cca.sex,colors,cca.head); ConnectionsHandler.getConnection().send(ccmsg); return true; case msg is CharacterCreationResultMessage: ccrmsg = msg as CharacterCreationResultMessage; this._kernel.processCallback(HookList.CharacterCreationResult,ccrmsg.result); return true; case msg is CharacterDeletionAction: cda = msg as CharacterDeletionAction; this._waitingForListRefreshAfterDeletion = true; cdrmsg = new CharacterDeletionRequestMessage(); cdrmsg.initCharacterDeletionRequestMessage(cda.id,MD5.hash(cda.id + ""~"" + cda.answer)); ConnectionsHandler.getConnection().send(cdrmsg); return true; case msg is CharacterDeletionErrorMessage: cdemsg = msg as CharacterDeletionErrorMessage; this._waitingForListRefreshAfterDeletion = false; reason = """"; if(cdemsg.reason == CharacterDeletionErrorEnum.DEL_ERR_TOO_MANY_CHAR_DELETION) { reason = ""TooManyDeletion""; } else if(cdemsg.reason == CharacterDeletionErrorEnum.DEL_ERR_BAD_SECRET_ANSWER) { reason = ""WrongAnswer""; } else if(cdemsg.reason == CharacterDeletionErrorEnum.DEL_ERR_RESTRICED_ZONE) { reason = ""UnsecureMode""; } this._kernel.processCallback(HookList.CharacterDeletionError,reason); this._requestedCharacterId = 0; return true; case msg is CharacterNameSuggestionRequestAction: cnsra = msg as CharacterNameSuggestionRequestAction; cnsrmsg = new CharacterNameSuggestionRequestMessage(); cnsrmsg.initCharacterNameSuggestionRequestMessage(); ConnectionsHandler.getConnection().send(cnsrmsg); return true; case msg is CharacterNameSuggestionSuccessMessage: cnssmsg = msg as CharacterNameSuggestionSuccessMessage; this._kernel.processCallback(HookList.CharacterNameSuggestioned,cnssmsg.suggestion); return true; case msg is CharacterNameSuggestionFailureMessage: cnsfmsg = msg as CharacterNameSuggestionFailureMessage; _log.error(""Generation de nom impossible !""); return true; case msg is CharacterSelectedForceMessage: if(!this._reconnectMsgSend) { Kernel.beingInReconection = true; characterId = CharacterSelectedForceMessage(msg).id; this._reconnectMsgSend = true; ConnectionsHandler.getConnection().send(new CharacterSelectedForceReadyMessage()); } return true; case msg is CharacterRemodelSelectionAction: crsa = msg as CharacterRemodelSelectionAction; remodel = new RemodelingInformation(); remodel.sex = crsa.sex; remodel.breed = crsa.breed; remodel.cosmeticId = crsa.cosmeticId; remodel.name = crsa.name; tempColorsArray = new Vector.(); for(colorIndex in crsa.colors) { colorInteger = int(crsa.colors[colorIndex]); if(colorInteger >= 0) { colorInteger &= 16777215; tempColorsArray.push(colorInteger | int(colorIndex) + 1 << 24); } } remodel.colors = tempColorsArray; if(PlayerManager.getInstance().server.gameTypeId == GameServerTypeEnum.SERVER_TYPE_HARDCORE || PlayerManager.getInstance().server.gameTypeId == GameServerTypeEnum.SERVER_TYPE_EPIC) { for each(person2 in this._charactersList) { if(person2.id == this._requestedToRemodelCharacterId) { if(person2.deathState == 1) { isReplay = true; } else if(person2.deathState == 0) { isReplay = false; } else { this.commonMod.openPopup(I18n.getUiText(""ui.common.error""),I18n.getUiText(""ui.common.cantSelectThisCharacterLimb""),[I18n.getUiText(""ui.common.ok"")]); } } } } else { isReplay = false; } if(isReplay) { crwrrmsg = new CharacterReplayWithRemodelRequestMessage(); crwrrmsg.initCharacterReplayWithRemodelRequestMessage(this._requestedToRemodelCharacterId,remodel); ConnectionsHandler.getConnection().send(crwrrmsg); } else { cswrmsg = new CharacterSelectionWithRemodelMessage(); cswrmsg.initCharacterSelectionWithRemodelMessage(this._requestedToRemodelCharacterId,remodel); ConnectionsHandler.getConnection().send(cswrmsg); } return true; case msg is CharacterDeselectionAction: this._requestedCharacterId = 0; return true; case msg is CharacterAutoConnectAction: characterToConnect = this.getCharacterToConnect(); currentServer = PlayerManager.getInstance().server; if(characterToConnect && currentServer) { this.launchAutoConnect(characterToConnect,currentServer); } break; case msg is CharacterSelectionAction: case msg is CharacterReplayRequestAction: if(this._requestedCharacterId) { return false; } bTutorial = false; if(msg is CharacterSelectionAction) { characterId = (msg as CharacterSelectionAction).characterId; bTutorial = (msg as CharacterSelectionAction).btutoriel; isReplay = false; } else if(msg is CharacterReplayRequestAction) { characterId = (msg as CharacterReplayRequestAction).characterId; bTutorial = false; isReplay = true; } this._requestedCharacterId = characterId; if(this._charactersToRemodelList[characterId]) { this._requestedToRemodelCharacterId = characterId; charToRemodel = this._charactersToRemodelList[characterId]; indexedColors = this.getCharacterColorsInformations(charToRemodel); char = CreationCharacterWrapper.create(charToRemodel.name,charToRemodel.sex,charToRemodel.breed,charToRemodel.cosmeticId,indexedColors); for each(perso in this._charactersList) { if(perso.id == characterId) { char.entityLook = perso.entityLook; } } modificationModules = []; if((charToRemodel.possibleChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_BREED) > 0) { modificationModules.push(""rebreed""); } if((charToRemodel.possibleChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_COLORS) > 0) { modificationModules.push(""recolor""); } if((charToRemodel.possibleChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_COSMETIC) > 0) { modificationModules.push(""relook""); } if((charToRemodel.possibleChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_NAME) > 0) { modificationModules.push(""rename""); } if((charToRemodel.possibleChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_GENDER) > 0) { modificationModules.push(""regender""); } mandatoryModules = []; if((charToRemodel.mandatoryChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_BREED) > 0) { mandatoryModules.push(""rebreed""); } if((charToRemodel.mandatoryChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_COLORS) > 0) { mandatoryModules.push(""recolor""); } if((charToRemodel.mandatoryChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_COSMETIC) > 0) { mandatoryModules.push(""relook""); } if((charToRemodel.mandatoryChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_NAME) > 0) { mandatoryModules.push(""rename""); } if((charToRemodel.mandatoryChangeMask & CharacterRemodelingEnum.CHARACTER_REMODELING_GENDER) > 0) { mandatoryModules.push(""regender""); } if((charToRemodel.mandatoryChangeMask & CharacterRemodelingEnum.CHARACTER_OPT_REMODELING_NAME) > 0) { modificationModules.push(""rename""); } this._kernel.processCallback(HookList.CharacterCreationStart,[modificationModules,mandatoryModules,char]); } else { this._requestedToRemodelCharacterId = 0; firstSelection = bTutorial; if(bTutorial) { cfsmsg = new CharacterFirstSelectionMessage(); cfsmsg.initCharacterFirstSelectionMessage(characterId,true); ConnectionsHandler.getConnection().send(cfsmsg); } else if(isReplay) { crrmsg = new CharacterReplayRequestMessage(); crrmsg.initCharacterReplayRequestMessage(characterId); ConnectionsHandler.getConnection().send(crrmsg); } else { csmsg = new CharacterSelectionMessage(); csmsg.initCharacterSelectionMessage(characterId); ConnectionsHandler.getConnection().send(csmsg); } } return true; break; case msg is CharacterSelectedSuccessMessage: cssmsg = msg as CharacterSelectedSuccessMessage; this._loadingStart = new Date().time; ConnectionsHandler.pause(); if(Kernel.getWorker().getFrame(ServerSelectionFrame)) { Kernel.getWorker().removeFrame(Kernel.getWorker().getFrame(ServerSelectionFrame)); } if(this._gmaf == null) { this._gmaf = new LoadingModuleFrame(); Kernel.getWorker().addFrame(this._gmaf); } PlayedCharacterManager.getInstance().infos = cssmsg.infos; DataStoreType.CHARACTER_ID = cssmsg.infos.id.toString(); Kernel.getWorker().pause(); this._cssmsg = cssmsg; UiModuleManager.getInstance().reset(); if(PlayerManager.getInstance().hasRights) { UiModuleManager.getInstance().init(Constants.PRE_GAME_MODULE,false); } else { UiModuleManager.getInstance().init(Constants.PRE_GAME_MODULE.concat(Constants.ADMIN_MODULE),false); } Dofus.getInstance().renameApp(cssmsg.infos.name + "" - Dofus "" + BuildInfos.VERSION.toStringForAppName()); ExternalNotificationManager.getInstance().init(); if(cssmsg.isCollectingStats) { StatisticsManager.getInstance().startStats(""shortcuts""); } else { StatisticsManager.getInstance().quit(); } if(cssmsg.infos.id == this._requestedToRemodelCharacterId) { for(j = 0; j < this._charactersList.length; j++) { bchar = this._charactersList[j]; if(bchar.id == cssmsg.infos.id) { this._charactersList[j] = BasicCharacterWrapper.create(bchar.id,cssmsg.infos.name,cssmsg.infos.level,cssmsg.infos.entityLook,cssmsg.infos.breed,cssmsg.infos.sex,0,0,bchar.bonusXp); break; } } } DebtManager.clean(); return true; case msg is AllModulesLoadedMessage: _log.warn(""GameServerApproachFrame AllModulesLoaded""); this._gmaf = null; isRelease = BuildInfos.BUILD_TYPE == BuildTypeEnum.RELEASE; LogLogger.activeLog(!isRelease || isRelease && DofusErrorHandler.debugManuallyActivated); Kernel.getWorker().addFrame(new WorldFrame()); Kernel.getWorker().addFrame(new AlignmentFrame()); Kernel.getWorker().addFrame(new SynchronisationFrame()); Kernel.getWorker().addFrame(new LivingObjectFrame()); Kernel.getWorker().addFrame(new AllianceFrame()); Kernel.getWorker().addFrame(new PlayedCharacterUpdatesFrame()); Kernel.getWorker().addFrame(new SocialFrame()); Kernel.getWorker().addFrame(new SpellInventoryManagementFrame()); Kernel.getWorker().addFrame(new InventoryManagementFrame()); Kernel.getWorker().addFrame(new ContextChangeFrame()); Kernel.getWorker().addFrame(new CommonUiFrame()); Kernel.getWorker().addFrame(new ProgressionFrame()); Kernel.getWorker().addFrame(new ChatFrame()); Kernel.getWorker().addFrame(new JobsFrame()); Kernel.getWorker().addFrame(new MountFrame()); Kernel.getWorker().addFrame(new EmoticonFrame()); Kernel.getWorker().addFrame(new QuestFrame()); Kernel.getWorker().addFrame(new TinselFrame()); Kernel.getWorker().addFrame(new PartyManagementFrame()); Kernel.getWorker().addFrame(new ProtectPishingFrame()); Kernel.getWorker().addFrame(new StackManagementFrame()); Kernel.getWorker().addFrame(new ExternalGameFrame()); Kernel.getWorker().addFrame(new AveragePricesFrame()); Kernel.getWorker().addFrame(new CameraControlFrame()); Kernel.getWorker().addFrame(new IdolsFrame()); Kernel.getWorker().addFrame(new RoleplayIntroductionFrame()); Kernel.getWorker().addFrame(new ScreenCaptureFrame()); Kernel.getWorker().addFrame(new AdministrablePopupFrame()); if(FeatureManager.getInstance().isFeatureWithKeywordEnabled(""character.spell.forgettable"")) { Kernel.getWorker().addFrame(new ForgettableSpellsUiFrame()); } if(!Kernel.getWorker().contains(HouseFrame)) { Kernel.getWorker().addFrame(new HouseFrame()); } Kernel.getWorker().removeFrame(Kernel.getWorker().getFrame(GameStartingFrame)); Kernel.getWorker().resume(); ConnectionsHandler.resume(); if(Kernel.beingInReconection && !this._reconnectMsgSend) { this._reconnectMsgSend = true; ConnectionsHandler.getConnection().send(new CharacterSelectedForceReadyMessage()); } if(InterClientManager.getInstance().flashKey && (!PlayerManager.getInstance() || PlayerManager.getInstance().server.id != 129 && PlayerManager.getInstance().server.id != 130)) { flashKeyMsg = new ClientKeyMessage(); flashKeyMsg.initClientKeyMessage(InterClientManager.getInstance().flashKey); ConnectionsHandler.getConnection().send(flashKeyMsg); } if(this._cssmsg != null) { PlayedCharacterManager.getInstance().infos = this._cssmsg.infos; DataStoreType.CHARACTER_ID = this._cssmsg.infos.id.toString(); } Kernel.getWorker().removeFrame(this); if(XmlConfig.getInstance().getBooleanEntry(""config.dev.mode"")) { ModuleDebugManager.display(XmlConfig.getInstance().getBooleanEntry(""config.dev.auto.display.controler"")); Console.getInstance().display(!XmlConfig.getInstance().getBooleanEntry(""config.dev.auto.display.eventUtil"")); ConsoleLUA.getInstance().display(!XmlConfig.getInstance().getBooleanEntry(""config.dev.auto.display.luaUtil"")); if(XmlConfig.getInstance().getBooleanEntry(""config.dev.auto.display.fpsManager"")) { FpsManager.getInstance().display(); fpsManagerState = XmlConfig.getInstance().getEntry(""config.dev.auto.display.fpsManager.state""); if(fpsManagerState) { for(i = 0; i < fpsManagerState; i++) { FpsManager.getInstance().changeState(); } } } } else { Console.logChatMessagesOnly = true; Console.getInstance().activate(); } this._kernel.processCallback(HookList.GameStart); Kernel.getWorker().addFrame(new ServerTransferFrame()); gccrmsg = new GameContextCreateRequestMessage(); ConnectionsHandler.getConnection().send(gccrmsg); soundApi = new SoundApi(); soundApi.stopIntroMusic(); Shortcut.loadSavedData(); devMode = LangManager.getInstance().getEntry(""config.dev.mode"") == ""true""; if(devMode) { luaPlayer = ScriptsManager.getInstance().getPlayer(ScriptsManager.LUA_PLAYER) as LuaPlayer; if(!luaPlayer) { luaPlayer = new LuaPlayer(); ScriptsManager.getInstance().addPlayer(ScriptsManager.LUA_PLAYER,luaPlayer); ScriptsManager.getInstance().addPlayerApi(luaPlayer,""EntityApi"",new EntityApi()); ScriptsManager.getInstance().addPlayerApi(luaPlayer,""SeqApi"",new ScriptSequenceApi()); ScriptsManager.getInstance().addPlayerApi(luaPlayer,""CameraApi"",new CameraApi()); } } if(BuildInfos.BUILD_TYPE != BuildTypeEnum.DEBUG) { if(OptionManager.getOptionManager(""dofus"").getOption(""optimizeMultiAccount"")) { if(InterClientManager.isMaster()) { new DataApi().initStaticCartographyData(); } } else { new DataApi().initStaticCartographyData(); } } now = new Date().time; delta = now - this._loadingStart; if(delta > this.LOADING_TIMEOUT) { tag = {}; tag.duration = uint(delta / 1000); _log.warn(""Client took too long to load ("" + tag.duration + ""s), reporting.""); DofusErrorHandler.captureMessage(""Client loading timeout."",tag,RavenClient.WARN); } ChatServiceManager.getInstance().tryToConnect(); return true; case msg is ConnectionResumedMessage: return true; case msg is CharacterSelectedErrorMessage: csemsg = msg as CharacterSelectedErrorMessage; this._kernel.processCallback(HookList.CharacterImpossibleSelection,this._requestedCharacterId); this._requestedCharacterId = 0; return true; case msg is BasicTimeMessage: btmsg = msg as BasicTimeMessage; date = new Date(); TimeManager.getInstance().serverTimeLag = btmsg.timestamp + btmsg.timezoneOffset * 60 * 1000 - date.getTime(); TimeManager.getInstance().serverUtcTimeLag = btmsg.timestamp - date.getTime(); TimeManager.getInstance().timezoneOffset = btmsg.timezoneOffset * 60 * 1000; TimeManager.getInstance().dofusTimeYearLag = -1370; return true; case msg is StartupActionsListMessage: salm = msg as StartupActionsListMessage; this._giftList = []; for each(gift in salm.actions) { _items = []; for each(item in gift.items) { iw = ItemWrapper.create(0,0,item.objectGID,item.quantity,item.effects,false); _items.push(iw); } oj = { ""uid"":gift.uid, ""title"":gift.title, ""text"":gift.text, ""items"":_items }; this._giftList.push(oj); } if(this._giftList.length) { this._charaListMinusDeadPeople = []; for each(perso in this._charactersList) { if(!perso.deathState || perso.deathState == 0) { this._charaListMinusDeadPeople.push(perso); } } if(!Berilia.getInstance().getUi(""characterSelection"")) { this._kernel.processCallback(HookList.CharacterSelectionStart,this._charactersList); } else { this._kernel.processCallback(HookList.CharactersListUpdated,this._charactersList); } } else { Kernel.getWorker().removeFrame(this); _log.warn(""Empty Gift List Received""); } return true; case msg is GiftAssignRequestAction: gar = msg as GiftAssignRequestAction; sao = new StartupActionsObjetAttributionMessage(); sao.initStartupActionsObjetAttributionMessage(gar.giftId,gar.characterId); ConnectionsHandler.getConnection().send(sao); return true; case msg is StartupActionFinishedMessage: safm = msg as StartupActionFinishedMessage; indexToDelete = -1; for each(giftAction in this._giftList) { if(giftAction.uid == safm.actionId) { indexToDelete = this._giftList.indexOf(giftAction); break; } } if(indexToDelete > -1) { this._giftList.splice(indexToDelete,1); KernelEventsManager.getInstance().processCallback(HookList.GiftAssigned,safm.actionId); } return true; case msg is ConsoleCommandsListMessage: cclMsg = msg as ConsoleCommandsListMessage; for(cmdIndex = 0; cmdIndex < cclMsg.aliases.length; cmdIndex++) { new ServerCommand(cclMsg.aliases[cmdIndex],cclMsg.descriptions[cmdIndex]); } return true; case msg is GameRolePlayArenaSwitchToFightServerMessage: if(Kernel.getWorker().contains(ServerTransferFrame)) { return false; } stf = new ServerTransferFrame(); Kernel.getWorker().addFrame(stf); return stf.process(msg); break; case msg is PopupWarningClosedMessage: KernelEventsManager.getInstance().processCallback(HookList.PopupWarningClosed); return true; case msg is PopupWarningCloseRequestAction: pwcrmsg = new PopupWarningCloseRequestMessage(); pwcrmsg.initPopupWarningCloseRequestMessage(); ConnectionsHandler.getConnection().send(pwcrmsg); return true; } return false; } public function pulled() : Boolean { return true; } private function getCharacterColorsInformations(ctrci:*) : Vector. { var uIndexedColor:Number = NaN; var uIndex:int = 0; var uColor:* = 0; if(!ctrci || !ctrci.colors) { return null; } var charColors:Vector. = new Vector.(); for(var ic:int = 0; ic < ProtocolConstantsEnum.MAX_PLAYER_COLOR; ic++) { charColors.push(-1); } var num:int = ctrci.colors.length; for(var i:int = 0; i < num; i++) { uIndexedColor = ctrci.colors[i]; uIndex = (uIndexedColor >> 24) - 1; uColor = uIndexedColor & 16777215; if(uIndex > -1 && uIndex < charColors.length) { charColors[uIndex] = uColor; } } return charColors; } private function onEscapePopup() : void { Kernel.getInstance().reset(); } private function requestCharactersList() : void { var clrmsg:CharactersListRequestMessage = new CharactersListRequestMessage(); if(ConnectionsHandler && ConnectionsHandler.getConnection()) { ConnectionsHandler.getConnection().send(clrmsg); } } private function getCharacterToConnect() : BasicCharacterWrapper { var charToConnect:BasicCharacterWrapper = null; var charToConnectSpecificallyId:Number = NaN; var ctc:BasicCharacterWrapper = null; if((Dofus.getInstance().options && Dofus.getInstance().options.getOption(""autoConnectType"") == 2 || PlayerManager.getInstance().autoConnectOfASpecificCharacterId > -1) && PlayerManager.getInstance().allowAutoConnectCharacter) { charToConnectSpecificallyId = PlayerManager.getInstance().autoConnectOfASpecificCharacterId; if(charToConnectSpecificallyId == -1) { if(this._charactersList.length <= 0) { return null; } charToConnect = this._charactersList[0]; } else { for each(ctc in this._charactersList) { if(ctc.id == charToConnectSpecificallyId) { charToConnect = ctc; break; } } } return charToConnect; } return null; } private function launchAutoConnect(charToConnect:BasicCharacterWrapper, server:Server) : void { var updateInformationDisplayed:String = null; var currentVersion:String = null; var fakacsa:CharacterSelectionAction = null; if(charToConnect && ((server.gameTypeId != GameServerTypeEnum.SERVER_TYPE_HARDCORE && server.gameTypeId != GameServerTypeEnum.SERVER_TYPE_EPIC || charToConnect.deathState == 0) && !SecureModeManager.getInstance().active && !this.isCharacterWaitingForChange(charToConnect.id) && !PlayerManager.getInstance().wasAlreadyConnected)) { this._openCharsList = false; this._kernel.processCallback(HookList.CharactersListUpdated,this._charactersList); updateInformationDisplayed = StoreDataManager.getInstance().getData(new DataStoreType(""ComputerModule_Ankama_Connection"",true,DataStoreEnum.LOCATION_LOCAL,DataStoreEnum.BIND_COMPUTER),""updateInformationDisplayed""); currentVersion = BuildInfos.VERSION.major.toString() + ""-"" + BuildInfos.VERSION.minor.toString(); if(updateInformationDisplayed == currentVersion) { fakacsa = new CharacterSelectionAction(); fakacsa.btutoriel = false; fakacsa.characterId = charToConnect.id; this.process(fakacsa); PlayerManager.getInstance().allowAutoConnectCharacter = false; } } } } } ",12091,False,2133.3337735384844,median "package com.company.assembleegameclient.objects { import com.company.assembleegameclient.map.Camera; import com.company.assembleegameclient.map.Square; import com.company.assembleegameclient.map.mapoverlay.CharacterStatusText; import com.company.assembleegameclient.objects.particles.HealingEffect; import com.company.assembleegameclient.objects.particles.LevelUpEffect; import com.company.assembleegameclient.parameters.Parameters; import com.company.assembleegameclient.parameters.Parameters; import com.company.assembleegameclient.sound.SoundEffectLibrary; import com.company.assembleegameclient.tutorial.Tutorial; import com.company.assembleegameclient.tutorial.doneAction; import com.company.assembleegameclient.util.AnimatedChar; import com.company.assembleegameclient.util.ConditionEffect; import com.company.assembleegameclient.util.FameUtil; import com.company.assembleegameclient.util.FreeList; import com.company.assembleegameclient.util.MaskedImage; import com.company.assembleegameclient.util.TextureRedrawer; import com.company.assembleegameclient.util.redrawers.GlowRedrawer; import com.company.util.CachingColorTransformer; import com.company.util.ConversionUtil; import com.company.util.GraphicsUtil; import com.company.util.IntPoint; import com.company.util.MoreColorUtil; import com.company.util.PointUtil; import com.company.util.Trig; import flash.display.BitmapData; import flash.display.GraphicsPath; import flash.display.GraphicsSolidFill; import flash.display.IGraphicsData; import flash.geom.ColorTransform; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Vector3D; import flash.utils.Dictionary; import flash.utils.getTimer; import kabam.rotmg.assets.services.CharacterFactory; import kabam.rotmg.chat.model.ChatMessage; import kabam.rotmg.constants.ActivationType; import kabam.rotmg.constants.GeneralConstants; import kabam.rotmg.constants.UseType; import kabam.rotmg.core.StaticInjectorContext; import kabam.rotmg.game.model.PotionInventoryModel; import kabam.rotmg.game.signals.AddTextLineSignal; import kabam.rotmg.game.view.components.QueuedStatusText; import kabam.rotmg.messaging.impl.data.StatData; import kabam.rotmg.stage3D.GraphicsFillExtra; import kabam.rotmg.text.model.NumberKey; import kabam.rotmg.text.model.TextKey; import kabam.rotmg.text.view.BitmapTextFactory; import kabam.rotmg.text.view.stringBuilder.LineBuilder; import kabam.rotmg.text.view.stringBuilder.StaticStringBuilder; import kabam.rotmg.text.view.stringBuilder.StringBuilder; import kabam.rotmg.ui.model.TabStripModel; import org.swiftsuspenders.Injector; public class Player extends Character { public static const MS_BETWEEN_TELEPORT:int = 10000; private static const MOVE_THRESHOLD:Number = 0.4; private static const NEARBY:Vector. = new [new Point(0, 0), new Point(1, 0), new Point(0, 1), new Point(1, 1)]; private static const RANK_OFFSET_MATRIX:Matrix = new Matrix(1, 0, 0, 1, 2, 2); private static const NAME_OFFSET_MATRIX:Matrix = new Matrix(1, 0, 0, 1, 20, 1); private static const MIN_MOVE_SPEED:Number = 0.004; private static const MAX_MOVE_SPEED:Number = 0.0096; private static const MIN_ATTACK_MULT:Number = 0.5; private static const MAX_ATTACK_MULT:Number = 2; private static const LOW_HEALTH_CT_OFFSET:int = 128; private static var lowHealthCT:Dictionary = new Dictionary(); public static var empiresCoin_:int = 0; public static var accountType_:int = 0; public static var isAdmin:Boolean = false; public static var isMod:Boolean = false; private static var newP:Point = new Point(); public var petObjectId:int = 0; public var petHpHealingAverageMin:int = 0; public var petHpHealingAverageMax:int = 0; public var petHpHealingAverageBonus:int = 0; public var petMpHealingAverageMin:int = 0; public var petMpHealingAverageMax:int = 0; public var petMpHealingAverageBonus:int = 0; public var petAttackCooldown:int = 0; public var petAttackChance:int = 0; public var petAttackDamageMin:int = 0; public var petAttackDamageMax:int = 0; public var isTrading:Boolean = false; public var xpTimer:int; public var skinId:int; public var skin:AnimatedChar; public var isShooting:Boolean; public var accountId_:String = """"; public var credits_:int = 0; public var tokens_:int = 0; public var numStars_:int = 0; public var fame_:int = 0; public var nameChosen_:Boolean = false; public var currFame_:int = 0; public var nextClassQuestFame_:int = -1; public var guildName_:String = null; public var guildRank_:int = -1; public var isFellowGuild_:Boolean = false; public var breath_:int = -1; public var maxMP_:int = 200; public var mp_:Number = 0; public var nextLevelExp_:int = 1000; public var exp_:int = 0; public var attack_:String = null; public var speed_:String = null; public var dexterity_:String = null; public var vitality_:String = null; public var wisdom_:String = null; public var maxHPBoost_:String = null; public var maxMPBoost_:String = null; public var attackBoost_:String = null; public var defenseBoost_:String = null; public var speedBoost_:String = null; public var vitalityBoost_:String = null; public var wisdomBoost_:String = null; public var dexterityBoost_:String = null; public var xpBoost_:int = 0; public var healthPotionCount_:int = 0; public var magicPotionCount_:int = 0; public var attackMax_:int = 0; public var defenseMax_:int = 0; public var speedMax_:int = 0; public var dexterityMax_:int = 0; public var vitalityMax_:int = 0; public var wisdomMax_:int = 0; public var maxHPMax_:int = 0; public var maxMPMax_:int = 0; public var hasBackpack_:Boolean = false; public var accountType_:int = 0; public var admin_:Boolean = false; public var starred_:Boolean = false; public var ignored_:Boolean = false; public var distSqFromThisPlayer_:Number = 0; protected var rotate_:Number = 0; protected var relMoveVec_:Point = null; protected var moveMultiplier_:Number = 1; public var attackPeriod_:Number = 0; public var attackAmount_:int = 0; public var isDazed_:Boolean = false; public var isBerserk_:Boolean = false; public var minAttackFrequency_:Number = 0; public var maxAttackFrequency_:Number = 0; public var weaponRateOfFire_:Number = 0; public var nextAltAttack_:int = 0; public var nextTeleportAt_:int = 0; public var dropBoost:int = 0; public var tierBoost:int = 0; protected var healingEffect_:HealingEffect = null; protected var nearestMerchant_:Merchant = null; public var isDefaultAnimatedChar:Boolean = true; public var projectileIdSetOverrideNew:String = """"; public var projectileIdSetOverrideOld:String = """"; private var addTextLine:AddTextLineSignal; private var factory:CharacterFactory; private var ip_:IntPoint; private var breathBackFill_:GraphicsSolidFill = null; private var breathBackPath_:GraphicsPath = null; private var breathFill_:GraphicsSolidFill = null; private var breathPath_:GraphicsPath = null; private var hallucinatingMaskedImage_:MaskedImage = null; private var slideVec_:Vector3D; public function Player(_arg1:XML) { this.minAttackFrequency_ = 0.0015; this.maxAttackFrequency_ = 0.008; this.ip_ = new IntPoint(); var _local2:Injector = StaticInjectorContext.getInjector(); this.addTextLine = _local2.getInstance(AddTextLineSignal); this.factory = _local2.getInstance(CharacterFactory); super(_arg1); this.attackMax_ = int(_arg1.Attack.@max); this.defenseMax_ = int(_arg1.Defense.@max); this.speedMax_ = int(_arg1.Speed.@max); this.dexterityMax_ = int(_arg1.Dexterity.@max); this.vitalityMax_ = int(_arg1.HpRegen.@max); this.wisdomMax_ = int(_arg1.MpRegen.@max); this.maxHPMax_ = int(_arg1.MaxHitPoints.@max); this.maxMPMax_ = int(_arg1.MaxMagicPoints.@max); texturingCache_ = new Dictionary(); this.slideVec_ = new Vector3D(); } public static function fromPlayerXML(name:String, playerXML:XML):Player { var _local3:int = int(playerXML.ObjectType); var _local4:XML = ObjectLibrary.xmlLibrary_[_local3]; var _local5:Player = new Player(_local4); _local5.name_ = name; _local5.level_ = int(playerXML.Level); _local5.exp_ = int(playerXML.Exp); _local5.equipment_ = ConversionUtil.toIntVector(playerXML.Equipment); _local5.calculateStatBoosts(); _local5.lockedSlot = new Vector.(_local5.equipment_.length); _local5.maxHP_ = (Parameters.parse(_local5.maxHPBoost_) + int(playerXML.MaxHitPoints)); _local5.hp_ = int(playerXML.HitPoints); _local5.maxMP_ = (Parameters.parse(_local5.maxMPBoost_) + int(playerXML.MaxMagicPoints)); _local5.mp_ = int(playerXML.MagicPoints); _local5.attack_ = (Parameters.parse(_local5.attackBoost_) + int(playerXML.Attack)).toString(); _local5.defense_ = (Parameters.parse(_local5.defenseBoost_) + int(playerXML.Defense)).toString(); _local5.speed_ = (Parameters.parse(_local5.speedBoost_) + int(playerXML.Speed)).toString(); _local5.dexterity_ = (Parameters.parse(_local5.vitalityBoost_) + int(playerXML.Dexterity)).toString(); _local5.vitality_ = (Parameters.parse(_local5.wisdomBoost_) + int(playerXML.HpRegen)).toString(); _local5.wisdom_ = (Parameters.parse(_local5.dexterityBoost_) + int(playerXML.MpRegen)).toString(); _local5.tex1Id_ = int(playerXML.Tex1); _local5.tex2Id_ = int(playerXML.Tex2); _local5.hasBackpack_ = int(playerXML.HasBackpack) != 0; return (_local5); } public function calculateStatBoosts():void { var _local2:int; var _local3:XML; var _local4:XML; var _local5:int; var _local6:int; this.maxHPBoost_ = ""0""; this.maxMPBoost_ = ""0""; this.attackBoost_ = ""0""; this.defenseBoost_ = ""0""; this.speedBoost_ = ""0""; this.vitalityBoost_ = ""0""; this.wisdomBoost_ = ""0""; this.dexterityBoost_ = ""0""; var _local1:uint; while (_local1 < GeneralConstants.NUM_EQUIPMENT_SLOTS) { if (((equipment_) && ((equipment_.length > _local1)))) { _local2 = equipment_[_local1]; if (_local2 != -1) { _local3 = ObjectLibrary.xmlLibrary_[_local2]; if (((!((_local3 == null))) && (_local3.hasOwnProperty(""ActivateOnEquip"")))) { for each (_local4 in _local3.ActivateOnEquip) { if (_local4.toString() == ""IncrementStat"") { _local5 = int(_local4.@stat); _local6 = int(_local4.@amount); switch (_local5) { case StatData.MAX_HP_STAT: this.maxHPBoost_ = (this.maxHPBoost_ + _local6); break; case StatData.MAX_MP_STAT: this.maxMPBoost_ = (this.maxMPBoost_ + _local6); break; case StatData.ATTACK_STAT: this.attackBoost_ = (Parameters.parse(this.attackBoost_) + _local6).toString(); break; case StatData.DEFENSE_STAT: this.defenseBoost_ = (Parameters.parse(this.defenseBoost_) + _local6).toString(); break; case StatData.SPEED_STAT: this.speedBoost_ = (Parameters.parse(this.speedBoost_) + _local6).toString(); break; case StatData.VITALITY_STAT: this.vitalityBoost_ = (Parameters.parse(this.vitalityBoost_) + _local6).toString(); break; case StatData.WISDOM_STAT: this.wisdomBoost_ = (Parameters.parse(this.wisdomBoost_) + _local6).toString(); break; case StatData.DEXTERITY_STAT: this.dexterityBoost_ = (Parameters.parse(this.dexterityBoost_) + _local6).toString(); break; } } } } } } _local1++; } } public function setRelativeMovement(_arg1:Number, _arg2:Number, _arg3:Number):void { var _local4:Number; if (this.relMoveVec_ == null) { this.relMoveVec_ = new Point(); } this.rotate_ = _arg1; this.relMoveVec_.x = _arg2; this.relMoveVec_.y = _arg3; if (isConfused()) { _local4 = this.relMoveVec_.x; this.relMoveVec_.x = -(this.relMoveVec_.y); this.relMoveVec_.y = -(_local4); this.rotate_ = -(this.rotate_); } } public function setCredits(_arg1:int):void { this.credits_ = _arg1; } public function setTokens(_arg1:int):void { this.tokens_ = _arg1; } public function setGuildName(_arg1:String):void { var _local3:GameObject; var _local4:Player; var _local5:Boolean; this.guildName_ = _arg1; var _local2:Player = map_.player_; if (_local2 == this) { for each (_local3 in map_.goDict_) { _local4 = (_local3 as Player); if (((!((_local4 == null))) && (!((_local4 == this))))) { _local4.setGuildName(_local4.guildName_); } } } else { _local5 = ((((((!((_local2 == null))) && (!((_local2.guildName_ == null))))) && (!((_local2.guildName_ == """"))))) && ((_local2.guildName_ == this.guildName_))); if (_local5 != this.isFellowGuild_) { this.isFellowGuild_ = _local5; nameBitmapData_ = null; } } } public function isTeleportEligible(_arg1:Player):Boolean { return (!(((_arg1.isPaused()) || (_arg1.isInvisible())))); } public function msUtilTeleport():int { var _local1:int = getTimer(); return (Math.max(0, (this.nextTeleportAt_ - _local1))); } public function teleportTo(_arg1:Player):Boolean { if (isPaused()) { this.addTextLine.dispatch(this.makeErrorMessage(TextKey.PLAYER_NOTELEPORTWHILEPAUSED)); return (false); } var _local2:int = this.msUtilTeleport(); if (_local2 > 0) { this.addTextLine.dispatch(this.makeErrorMessage(TextKey.PLAYER_TELEPORT_COOLDOWN, {""seconds"": int(((_local2 / 1000) + 1))})); return (false); } if (!this.isTeleportEligible(_arg1)) { if (_arg1.isInvisible()) { this.addTextLine.dispatch(this.makeErrorMessage(TextKey.TELEPORT_INVISIBLE_PLAYER, {""player"": _arg1.name_})); } else { this.addTextLine.dispatch(this.makeErrorMessage(TextKey.PLAYER_TELEPORT_TO_PLAYER, {""player"": _arg1.name_})); } return (false); } map_.gs_.gsc_.playerText(""/teleport "" + _arg1.name_); this.nextTeleportAt_ = (getTimer() + MS_BETWEEN_TELEPORT); return (true); } private function makeErrorMessage(_arg1:String, _arg2:Object = null):ChatMessage { return (ChatMessage.make(Parameters.ERROR_CHAT_NAME, _arg1, -1, -1, """", false, _arg2)); } public function levelUpEffect(_arg1:String, _arg2:Boolean = true):void { if (_arg2) { this.levelUpParticleEffect(); } var _local3:QueuedStatusText = new QueuedStatusText(this, new LineBuilder().setParams(_arg1), 0xFF00, 2000); map_.mapOverlay_.addQueuedText(_local3); } public function handleLevelUp(_arg1:Boolean):void { SoundEffectLibrary.play(""level_up""); if (_arg1) { this.levelUpEffect(TextKey.PLAYER_NEWCLASSUNLOCKED, false); this.levelUpEffect(TextKey.PLAYER_LEVELUP); } else { this.levelUpEffect(TextKey.PLAYER_LEVELUP); } } public function levelUpParticleEffect(_arg1:uint = 0xFF00FF00):void { map_.addObj(new LevelUpEffect(this, _arg1, 20), x_, y_); } public function handleExpUp(_arg1:int):void { if (level_ == 20) { return; } var _local2:CharacterStatusText = new CharacterStatusText(this, 0xFF00, 1000); _local2.setStringBuilder(new LineBuilder().setParams(TextKey.PLAYER_EXP, {""exp"": _arg1})); map_.mapOverlay_.addStatusText(_local2); } private function getNearbyMerchant():Merchant { var _local3:Point; var _local4:Merchant; var _local1:int = ((((x_ - int(x_))) > 0.5) ? 1 : -1); var _local2:int = ((((y_ - int(y_))) > 0.5) ? 1 : -1); for each (_local3 in NEARBY) { this.ip_.x_ = (x_ + (_local1 * _local3.x)); this.ip_.y_ = (y_ + (_local2 * _local3.y)); _local4 = map_.merchLookup_[this.ip_]; if (_local4 != null) { return ((((PointUtil.distanceSquaredXY(_local4.x_, _local4.y_, x_, y_) < 1)) ? _local4 : null)); } } return (null); } public function walkTo(_arg1:Number, _arg2:Number):Boolean { this.modifyMove(_arg1, _arg2, newP); return (this.moveTo(newP.x, newP.y)); } override public function moveTo(_arg1:Number, _arg2:Number):Boolean { var _local3:Boolean = super.moveTo(_arg1, _arg2); if (map_.gs_.evalIsNotInCombatMapArea()) { this.nearestMerchant_ = this.getNearbyMerchant(); } return (_local3); } public function modifyMove(_arg1:Number, _arg2:Number, _arg3:Point):void { if (((isParalyzed()) || (isPetrified()))) { _arg3.x = x_; _arg3.y = y_; return; } var _local4:Number = (_arg1 - x_); var _local5:Number = (_arg2 - y_); if ((((((((_local4 < MOVE_THRESHOLD)) && ((_local4 > -(MOVE_THRESHOLD))))) && ((_local5 < MOVE_THRESHOLD)))) && ((_local5 > -(MOVE_THRESHOLD))))) { this.modifyStep(_arg1, _arg2, _arg3); return; } var _local6:Number = (MOVE_THRESHOLD / Math.max(Math.abs(_local4), Math.abs(_local5))); var _local7:Number = 0; _arg3.x = x_; _arg3.y = y_; var _local8:Boolean; while (!(_local8)) { if ((_local7 + _local6) >= 1) { _local6 = (1 - _local7); _local8 = true; } this.modifyStep((_arg3.x + (_local4 * _local6)), (_arg3.y + (_local5 * _local6)), _arg3); _local7 = (_local7 + _local6); } } public function modifyStep(_arg1:Number, _arg2:Number, _arg3:Point):void { var _local6:Number; var _local7:Number; var _local4:Boolean = ((((((x_ % 0.5) == 0)) && (!((_arg1 == x_))))) || (!((int((x_ / 0.5)) == int((_arg1 / 0.5)))))); var _local5:Boolean = ((((((y_ % 0.5) == 0)) && (!((_arg2 == y_))))) || (!((int((y_ / 0.5)) == int((_arg2 / 0.5)))))); if (((((!(_local4)) && (!(_local5)))) || (this.isValidPosition(_arg1, _arg2)))) { _arg3.x = _arg1; _arg3.y = _arg2; return; } if (_local4) { _local6 = (((_arg1) > x_) ? (int((_arg1 * 2)) / 2) : (int((x_ * 2)) / 2)); if (int(_local6) > int(x_)) { _local6 = (_local6 - 0.01); } } if (_local5) { _local7 = (((_arg2) > y_) ? (int((_arg2 * 2)) / 2) : (int((y_ * 2)) / 2)); if (int(_local7) > int(y_)) { _local7 = (_local7 - 0.01); } } if (!_local4) { _arg3.x = _arg1; _arg3.y = _local7; if (((!((square_ == null))) && (!((square_.props_.slideAmount_ == 0))))) { this.resetMoveVector(false); } return; } if (!_local5) { _arg3.x = _local6; _arg3.y = _arg2; if (((!((square_ == null))) && (!((square_.props_.slideAmount_ == 0))))) { this.resetMoveVector(true); } return; } var _local8:Number = (((_arg1) > x_) ? (_arg1 - _local6) : (_local6 - _arg1)); var _local9:Number = (((_arg2) > y_) ? (_arg2 - _local7) : (_local7 - _arg2)); if (_local8 > _local9) { if (this.isValidPosition(_arg1, _local7)) { _arg3.x = _arg1; _arg3.y = _local7; return; } if (this.isValidPosition(_local6, _arg2)) { _arg3.x = _local6; _arg3.y = _arg2; return; } } else { if (this.isValidPosition(_local6, _arg2)) { _arg3.x = _local6; _arg3.y = _arg2; return; } if (this.isValidPosition(_arg1, _local7)) { _arg3.x = _arg1; _arg3.y = _local7; return; } } _arg3.x = _local6; _arg3.y = _local7; } private function resetMoveVector(_arg1:Boolean):void { moveVec_.scaleBy(-0.5); if (_arg1) { moveVec_.y = (moveVec_.y * -1); } else { moveVec_.x = (moveVec_.x * -1); } } public function isValidPosition(_arg1:Number, _arg2:Number):Boolean { var _local3:Square = map_.getSquare(_arg1, _arg2); if (((!((square_ == _local3))) && ((((_local3 == null)) || (!(_local3.isWalkable())))))) { return (false); } var _local4:Number = (_arg1 - int(_arg1)); var _local5:Number = (_arg2 - int(_arg2)); if (_local4 < 0.5) { if (this.isFullOccupy((_arg1 - 1), _arg2)) { return (false); } if (_local5 < 0.5) { if (((this.isFullOccupy(_arg1, (_arg2 - 1))) || (this.isFullOccupy((_arg1 - 1), (_arg2 - 1))))) { return (false); } } else { if (_local5 > 0.5) { if (((this.isFullOccupy(_arg1, (_arg2 + 1))) || (this.isFullOccupy((_arg1 - 1), (_arg2 + 1))))) { return (false); } } } } else { if (_local4 > 0.5) { if (this.isFullOccupy((_arg1 + 1), _arg2)) { return (false); } if (_local5 < 0.5) { if (((this.isFullOccupy(_arg1, (_arg2 - 1))) || (this.isFullOccupy((_arg1 + 1), (_arg2 - 1))))) { return (false); } } else { if (_local5 > 0.5) { if (((this.isFullOccupy(_arg1, (_arg2 + 1))) || (this.isFullOccupy((_arg1 + 1), (_arg2 + 1))))) { return (false); } } } } else { if (_local5 < 0.5) { if (this.isFullOccupy(_arg1, (_arg2 - 1))) { return (false); } } else { if (_local5 > 0.5) { if (this.isFullOccupy(_arg1, (_arg2 + 1))) { return (false); } } } } } return (true); } public function isFullOccupy(_arg1:Number, _arg2:Number):Boolean { var _local3:Square = map_.lookupSquare(_arg1, _arg2); return ((((((_local3 == null)) || ((_local3.tileType_ == 0xFF)))) || (((!((_local3.obj_ == null))) && (_local3.obj_.props_.fullOccupy_))))); } override public function update(currentTime:int, deltaMS:int):Boolean { if (this.tierBoost && !isPaused()) { this.tierBoost = this.tierBoost - deltaMS; if (this.tierBoost < 0) { this.tierBoost = 0; } } if (this.dropBoost && !isPaused()) { this.dropBoost = this.dropBoost - deltaMS; if (this.dropBoost < 0) { this.dropBoost = 0; } } if (this.xpTimer && !isPaused()) { this.xpTimer = this.xpTimer - deltaMS; if (this.xpTimer < 0) { this.xpTimer = 0; } } if (isHealing() && !isPaused()) { if (this.healingEffect_ == null) { this.healingEffect_ = new HealingEffect(this); map_.addObj(this.healingEffect_, x_, y_); } } else { if (this.healingEffect_ != null) { map_.removeObj(this.healingEffect_.objectId_); this.healingEffect_ = null; } } var angle:Number = Parameters.data_.cameraAngle; if (this.rotate_ != 0) { angle = angle + deltaMS * Parameters.PLAYER_ROTATE_SPEED * this.rotate_; Parameters.data_.cameraAngle = angle; } if (map_.player_ == this && isPaused()) { return true; } if (this.relMoveVec_ != null) { if (this.relMoveVec_.x != 0 || this.relMoveVec_.y != 0) { var mvSpd:Number = this.getMoveSpeed(); var mvAngle:Number = Math.atan2(this.relMoveVec_.y, this.relMoveVec_.x); if (square_.props_.slideAmount_ > 0) { slideVec_.x = mvSpd * Math.cos(angle + mvAngle); slideVec_.y = mvSpd * Math.sin(angle + mvAngle); slideVec_.z = 0; moveVec_.scaleBy(square_.props_.slideAmount_); if (moveVec_.length < slideVec_.length) { slideVec_.scaleBy(1 - square_.props_.slideAmount_); moveVec_ = moveVec_.add(slideVec_); } } else { moveVec_.x = mvSpd * Math.cos(angle + mvAngle); moveVec_.y = mvSpd * Math.sin(angle + mvAngle); } } else { if (moveVec_.length > 0.00012 && square_.props_.slideAmount_ > 0) { moveVec_.scaleBy(square_.props_.slideAmount_); } else { moveVec_.x = 0; moveVec_.y = 0; } } if (square_ != null && square_.props_.push_) { moveVec_.x = moveVec_.x - square_.props_.animate_.dx_ / 1000; moveVec_.y = moveVec_.y - square_.props_.animate_.dy_ / 1000; } this.walkTo(x_ + deltaMS * moveVec_.x, y_ + deltaMS * moveVec_.y); } else { if (!super.update(currentTime, deltaMS)) { return false; } } if (map_.player_ == this && square_.props_.maxDamage_ > 0 && (square_.lastDamage_ + 500) < currentTime && !isInvincible() && (square_.obj_ == null || !square_.obj_.props_.protectFromGroundDamage_)) { var dmg:int = map_.gs_.gsc_.getNextDamage(square_.props_.minDamage_, square_.props_.maxDamage_); var conditionEffects:Vector. = new Vector.(); conditionEffects.push(ConditionEffect.GROUND_DAMAGE); damage(-1, dmg, conditionEffects, hp_ <= dmg, null); map_.gs_.gsc_.groundDamage(currentTime, x_, y_); square_.lastDamage_ = currentTime; } return true; } public function onMove():void { if (map_ == null) { return; } var _local1:Square = map_.getSquare(x_, y_); if (_local1.props_.sinking_) { sinkLevel_ = Math.min((sinkLevel_ + 1), Parameters.MAX_SINK_LEVEL); this.moveMultiplier_ = (0.1 + ((1 - (sinkLevel_ / Parameters.MAX_SINK_LEVEL)) * (_local1.props_.speed_ - 0.1))); } else { sinkLevel_ = 0; this.moveMultiplier_ = _local1.props_.speed_; } } override protected function makeNameBitmapData():BitmapData { var _local1:StringBuilder = new StaticStringBuilder(name_); var _local2:BitmapTextFactory = StaticInjectorContext.getInjector().getInstance(BitmapTextFactory); var _local3:BitmapData = _local2.make(_local1, 16, this.getNameColor(), true, NAME_OFFSET_MATRIX, true); _local3.draw(FameUtil.numStarsToIcon(this.numStars_), RANK_OFFSET_MATRIX); return (_local3); } private function getNameColor():uint { if (this.isFellowGuild_) { return (Parameters.FELLOW_GUILD_COLOR); } if (this.nameChosen_) { return (Parameters.NAME_CHOSEN_COLOR); } return (0xFFFFFF); } protected function drawBreathBar(_arg1:Vector., _arg2:int):void { var _local7:Number; var _local8:Number; if (this.breathPath_ == null) { this.breathBackFill_ = new GraphicsSolidFill(); this.breathBackPath_ = new GraphicsPath(GraphicsUtil.QUAD_COMMANDS, new Vector.()); this.breathFill_ = new GraphicsSolidFill(2542335); this.breathPath_ = new GraphicsPath(GraphicsUtil.QUAD_COMMANDS, new Vector.()); } if (this.breath_ <= Parameters.BREATH_THRESH) { _local7 = ((Parameters.BREATH_THRESH - this.breath_) / Parameters.BREATH_THRESH); this.breathBackFill_.color = MoreColorUtil.lerpColor(0x545454, 0xFF0000, (Math.abs(Math.sin((_arg2 / 300))) * _local7)); } else { this.breathBackFill_.color = 0x545454; } var _local3:int = 20; var _local4:int = 8; var _local5:int = 6; var _local6:Vector. = (this.breathBackPath_.data as Vector.); _local6.length = 0; _local6.push((posS_[0] - _local3), (posS_[1] + _local4), (posS_[0] + _local3), (posS_[1] + _local4), (posS_[0] + _local3), ((posS_[1] + _local4) + _local5), (posS_[0] - _local3), ((posS_[1] + _local4) + _local5)); _arg1.push(this.breathBackFill_); _arg1.push(this.breathBackPath_); _arg1.push(GraphicsUtil.END_FILL); if (this.breath_ > 0) { _local8 = (((this.breath_ / 100) * 2) * _local3); this.breathPath_.data.length = 0; _local6 = (this.breathPath_.data as Vector.); _local6.length = 0; _local6.push((posS_[0] - _local3), (posS_[1] + _local4), ((posS_[0] - _local3) + _local8), (posS_[1] + _local4), ((posS_[0] - _local3) + _local8), ((posS_[1] + _local4) + _local5), (posS_[0] - _local3), ((posS_[1] + _local4) + _local5)); _arg1.push(this.breathFill_); _arg1.push(this.breathPath_); _arg1.push(GraphicsUtil.END_FILL); } GraphicsFillExtra.setSoftwareDrawSolid(this.breathFill_, true); GraphicsFillExtra.setSoftwareDrawSolid(this.breathBackFill_, true); } override public function draw(_arg1:Vector., _arg2:Camera, _arg3:int):void { super.draw(_arg1, _arg2, _arg3); if (this != map_.player_) { if (!Parameters.screenShotMode_) { drawName(_arg1, _arg2); } } else { if (this.breath_ >= 0) { this.drawBreathBar(_arg1, _arg3); } } } private function getMoveSpeed():Number { if (isSlowed()) { return ((MIN_MOVE_SPEED * this.moveMultiplier_)); } var _local1:Number = (MIN_MOVE_SPEED + ((Parameters.parse(this.speed_) / 75) * (MAX_MOVE_SPEED - MIN_MOVE_SPEED))); if (((isSpeedy()) || (isNinjaSpeedy()))) { _local1 = (_local1 * 1.5); } return ((_local1 * this.moveMultiplier_)); } public function attackFrequency():Number { this.isDazed_ = isDazed(); this.isBerserk_ = isBerserk(); if (this.isDazed_) return this.minAttackFrequency_; var _rateOfFire:Number = this.minAttackFrequency_ + ((Parameters.parse(this.dexterity_) / 75) * (this.maxAttackFrequency_ - this.minAttackFrequency_)); if (this.isBerserk_) _rateOfFire *= 1.5; return (_rateOfFire); } private function attackMultiplier():Number { if (isWeak()) { return (MIN_ATTACK_MULT); } var _local1:Number = (MIN_ATTACK_MULT + ((Parameters.parse(this.attack_) / 75) * (MAX_ATTACK_MULT - MIN_ATTACK_MULT))); if (isDamaging()) { _local1 = (_local1 * 1.5); } return (_local1); } private function makeSkinTexture():void { var _local1:MaskedImage = this.skin.imageFromAngle(0, AnimatedChar.STAND, 0); animatedChar_ = this.skin; texture_ = _local1.image_; mask_ = _local1.mask_; this.isDefaultAnimatedChar = true; } private function setToRandomAnimatedCharacter():void { var _local1:Vector. = ObjectLibrary.hexTransforms_; var _local2:uint = Math.floor((Math.random() * _local1.length)); var _local3:int = _local1[_local2].@type; var _local4:TextureData = ObjectLibrary.typeToTextureData_[_local3]; texture_ = _local4.texture_; mask_ = _local4.mask_; animatedChar_ = _local4.animatedChar_; this.isDefaultAnimatedChar = false; } override protected function getTexture(camera:Camera, currentTime:int):BitmapData { var pos:Number = 0; var action:int = AnimatedChar.STAND; if (this.isShooting || currentTime < (attackStart_ + this.attackPeriod_)) { facing_ = attackAngle_; pos = ((currentTime - attackStart_) % this.attackPeriod_) / this.attackPeriod_; action = AnimatedChar.ATTACK; } else { if (moveVec_.x != 0 || moveVec_.y != 0) { var movPeriod:int = 3.5 / this.getMoveSpeed(); if (moveVec_.y != 0 || moveVec_.x != 0) { facing_ = Math.atan2(moveVec_.y, moveVec_.x); } pos = (currentTime % movPeriod) / movPeriod; action = AnimatedChar.WALK; } } if (this.isHexed()) { this.isDefaultAnimatedChar && this.setToRandomAnimatedCharacter(); } else { if (!this.isDefaultAnimatedChar) { this.makeSkinTexture(); } } var maskImg:MaskedImage; if (camera.isHallucinating_) { maskImg = getHallucinatingMaskedImage(); } else { maskImg = animatedChar_.imageFromFacing(facing_, camera, action, pos); } var tex1Id:int = tex1Id_; var tex2Id:int = tex2Id_; var tex:BitmapData; if (this.nearestMerchant_) { var merchDict:Dictionary = texturingCache_[this.nearestMerchant_]; if (merchDict == null) { texturingCache_[this.nearestMerchant_] = new Dictionary(); } else { tex = merchDict[maskImg]; } tex1Id = this.nearestMerchant_.getTex1Id(tex1Id_); tex2Id = this.nearestMerchant_.getTex2Id(tex2Id_); } else { tex = texturingCache_[maskImg]; } if (tex == null) { tex = TextureRedrawer.resize(maskImg.image_, maskImg.mask_, size_, false, tex1Id, tex2Id); if (this.nearestMerchant_ != null) { texturingCache_[this.nearestMerchant_][maskImg] = tex; } else { texturingCache_[maskImg] = tex; } } if (hp_ < maxHP_ * 0.2) { var intensity:Number = int(Math.abs(Math.sin(currentTime / 200)) * 10) / 10; var ct:ColorTransform = lowHealthCT[intensity]; if (ct == null) { ct = new ColorTransform(1, 1, 1, 1, intensity * LOW_HEALTH_CT_OFFSET, -intensity * LOW_HEALTH_CT_OFFSET, -intensity * LOW_HEALTH_CT_OFFSET); lowHealthCT[intensity] = ct; } tex = CachingColorTransformer.transformBitmapData(tex, ct); } var plrTex:BitmapData = texturingCache_[tex]; if (plrTex == null) { plrTex = GlowRedrawer.outlineGlow(tex, this.glowColor_); texturingCache_[tex] = plrTex; } if (isPaused() || isStasis() || isPetrified()) { plrTex = CachingColorTransformer.filterBitmapData(plrTex, PAUSED_FILTER); } else { if (isInvisible()) { plrTex = CachingColorTransformer.alphaBitmapData(plrTex, 40); } } return plrTex; } private function getHallucinatingMaskedImage():MaskedImage { if (hallucinatingMaskedImage_ == null) { hallucinatingMaskedImage_ = new MaskedImage(getHallucinatingTexture(), null); } return hallucinatingMaskedImage_; } override public function getPortrait():BitmapData { var _local1:MaskedImage; var _local2:int; if (portrait_ == null) { _local1 = animatedChar_.imageFromDir(AnimatedChar.RIGHT, AnimatedChar.STAND, 0); _local2 = ((4 / _local1.image_.width) * 100); portrait_ = TextureRedrawer.resize(_local1.image_, _local1.mask_, _local2, true, tex1Id_, tex2Id_); portrait_ = GlowRedrawer.outlineGlow(portrait_, 0); } return (portrait_); } public function useAltWeapon(_arg1:Number, _arg2:Number, _arg3:int):Boolean { var _local7:XML; var _local8:int; var _local9:Number; var _local10:int; var _local11:int; if ((((map_ == null)) || (isPaused()))) { return (false); } var _local4:int = equipment_[1]; if (_local4 == -1) { return (false); } var _local5:XML = ObjectLibrary.xmlLibrary_[_local4]; if ((((_local5 == null)) || (!(_local5.hasOwnProperty(""Usable""))))) { return (false); } var _local6:Point = map_.pSTopW(_arg1, _arg2); if (_local6 == null) { SoundEffectLibrary.play(""error""); return (false); } for each (_local7 in _local5.Activate) { if (_local7.toString() == ActivationType.TELEPORT) { if (!this.isValidPosition(_local6.x, _local6.y)) { SoundEffectLibrary.play(""error""); return (false); } } } _local8 = getTimer(); if (_arg3 == UseType.START_USE) { if (_local8 < this.nextAltAttack_) { SoundEffectLibrary.play(""error""); return (false); } _local10 = int(_local5.MpCost); if (_local10 > this.mp_) { SoundEffectLibrary.play(""no_mana""); return (false); } _local11 = 500; if (_local5.hasOwnProperty(TextKey.COOLDOWN)) { _local11 = (Number(_local5.Cooldown) * NumberKey.COOLDOWNVALUE); } this.nextAltAttack_ = (_local8 + _local11); map_.gs_.gsc_.useItem(_local8, objectId_, 1, _local4, _local6.x, _local6.y, _arg3, isTrading); if (_local5.Activate == ActivationType.SHOOT) { _local9 = Math.atan2(_arg2, _arg1); this.doShoot(_local4, _local5, (Parameters.data_.cameraAngle + _local9), false); } } else { if (_local5.hasOwnProperty(""MultiPhase"")) { map_.gs_.gsc_.useItem(_local8, objectId_, 1, _local4, _local6.x, _local6.y, _arg3, isTrading); _local10 = int(_local5.MpEndCost); if (_local10 <= this.mp_) { _local9 = Math.atan2(_arg2, _arg1); this.doShoot(_local4, _local5, (Parameters.data_.cameraAngle + _local9), false); } } } return (true); } public function attemptAttackAngle(_arg1:Number):void { this.shoot((Parameters.data_.cameraAngle + _arg1)); } override public function setAttack(_arg1:int, _arg2:Number):void { var _local3:XML = ObjectLibrary.xmlLibrary_[_arg1]; if ((((_local3 == null)) || (!(_local3.hasOwnProperty(TextKey.RATEOFFIRE))))) { return; } var _local4:Number = Number(_local3.RateOfFire); this.attackPeriod_ = ((NumberKey.RATEOFFIREVALUE / this.attackFrequency()) * (NumberKey.RATEOFFIREVALUE / _local4)); super.setAttack(_arg1, _arg2); } private function shoot(angle:Number):void { if (map_ == null || isStunned() || isPaused() || isPetrified()) return; var weapType:int = this.equipment_[0]; if (weapType == -1) return; var weapon:XML = ObjectLibrary.xmlLibrary_[weapType]; var curTime:int = getTimer(); this.weaponRateOfFire_ = Number(weapon.RateOfFire); this.attackPeriod_ = (NumberKey.RATEOFFIREVALUE / this.attackFrequency()) * (NumberKey.RATEOFFIREVALUE / this.weaponRateOfFire_); if (curTime < this.attackStart_ + this.attackPeriod_) return; doneAction(map_.gs_, Tutorial.ATTACK_ACTION); this.attackAngle_ = angle; this.attackStart_ = curTime; this.doShoot(weapType, weapon, attackAngle_, true); } private function doShoot(weaponType:int, weaponXML:XML, attackAngle:Number, isShooting:Boolean):void { var _local11:uint; var _local12:Projectile; var _local13:int; var _local14:int; var _local15:Number; var _local16:int; var arcGap:Number = (weaponXML.hasOwnProperty(TextKey.ARCGAP) ? Number(weaponXML.ArcGap) : NumberKey.ARCGAPVALUE) * Trig.toRadians; var _local8:Number = (arcGap * (this.attackAmount_ - 1)); var _local9:Number = (attackAngle - (_local8 / 2)); this.isShooting = isShooting; this.attackAmount_ = weaponXML.hasOwnProperty(TextKey.NUMPROJECTILES) ? int(weaponXML.NumProjectiles) : NumberKey.NUMPROJECTILESVALUE; var _local10:int; while (_local10 < this.attackAmount_) { _local11 = getBulletId(); _local12 = (FreeList.newObject(Projectile) as Projectile); if (((isShooting) && (!((this.projectileIdSetOverrideNew == """"))))) { _local12.reset(weaponType, 0, objectId_, _local11, _local9, this.attackStart_, this.projectileIdSetOverrideNew, this.projectileIdSetOverrideOld); } else { _local12.reset(weaponType, 0, objectId_, _local11, _local9, this.attackStart_); } _local13 = int(_local12.projProps_.minDamage_); _local14 = int(_local12.projProps_.maxDamage_); _local15 = ((isShooting) ? this.attackMultiplier() : 1); _local16 = (map_.gs_.gsc_.getNextDamage(_local13, _local14) * _local15); _local12.setDamage(_local16); if ((((_local10 == 0)) && (!((_local12.sound_ == null))))) { SoundEffectLibrary.play(_local12.sound_, 0.75, false); } map_.addObj(_local12, (x_ + (Math.cos(attackAngle) * 0.3)), (y_ + (Math.sin(attackAngle) * 0.3))); map_.gs_.gsc_.playerShoot(_local12, this.attackAmount_, this.isDazed_, this.isBerserk_, this.minAttackFrequency_, this.maxAttackFrequency_, this.weaponRateOfFire_); _local9 = (_local9 + arcGap); _local10++; } } public function isHexed():Boolean { return (!(((condition_[ConditionEffect.CE_FIRST_BATCH] & ConditionEffect.HEXED_BIT) == 0))); } public function isInventoryFull():Boolean { if (equipment_ == null) { return (false); } var _local1:int = equipment_.length; var _local2:uint = 4; while (_local2 < _local1) { if (equipment_[_local2] <= 0) { return (false); } _local2++; } return (true); } public function nextAvailableInventorySlot():int { var _local1:int = ((this.hasBackpack_) ? equipment_.length : (equipment_.length - GeneralConstants.NUM_INVENTORY_SLOTS)); var _local2:uint = 4; while (_local2 < _local1) { if (equipment_[_local2] <= 0) { return (_local2); } _local2++; } return (-1); } public function numberOfAvailableSlots():int { var _local1:int = ((this.hasBackpack_) ? equipment_.length : (equipment_.length - GeneralConstants.NUM_INVENTORY_SLOTS)); var _local2:int; var _local3:uint = 4; while (_local3 < _local1) { if (equipment_[_local3] <= 0) { _local2++; } _local3++; } return (_local2); } public function swapInventoryIndex(_arg1:String):int { var _local2:int; var _local3:int; if (!this.hasBackpack_) { return (-1); } if (_arg1 == TabStripModel.BACKPACK) { _local2 = GeneralConstants.NUM_EQUIPMENT_SLOTS; _local3 = (GeneralConstants.NUM_EQUIPMENT_SLOTS + GeneralConstants.NUM_INVENTORY_SLOTS); } else { _local2 = (GeneralConstants.NUM_EQUIPMENT_SLOTS + GeneralConstants.NUM_INVENTORY_SLOTS); _local3 = equipment_.length; } var _local4:uint = _local2; while (_local4 < _local3) { if (equipment_[_local4] <= 0) { return (_local4); } _local4++; } return (-1); } public function getPotionCount(_arg1:int):int { switch (_arg1) { case PotionInventoryModel.HEALTH_POTION_ID: return (this.healthPotionCount_); case PotionInventoryModel.MAGIC_POTION_ID: return (this.magicPotionCount_); } return (0); } public function getTex1():int { return (tex1Id_); } public function getTex2():int { return (tex2Id_); } } } ",12121,False,2136.871295262328,median "/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the ""License""); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import BaseRule; createTable : CREATE createTableSpecification TABLE tableName createSharingClause createDefinitionClause createMemOptimizeClause createParentClause ; createEdition : CREATE EDITION editionName (AS CHILD OF editionName)? ; createIndex : CREATE createIndexSpecification INDEX indexName ON createIndexDefinitionClause usableSpecification? invalidationSpecification? ; alterTable : ALTER TABLE tableName memOptimizeClause alterDefinitionClause enableDisableClauses ; alterIndex : ALTER INDEX indexName alterIndexInformationClause ; alterTrigger : ALTER TRIGGER triggerName ( | triggerCompileClause | ( ENABLE | DISABLE) | RENAME TO name | (EDITIONABLE | NONEDITIONABLE) ) ; triggerCompileClause : COMPILE DEBUG? (compilerParametersClause*)? (REUSE SETTINGS)? ; compilerParametersClause : parameterName EQ_ parameterValue ; dropTable : DROP TABLE tableName (CASCADE CONSTRAINTS)? (PURGE)? ; dropPackage : DROP PACKAGE BODY? packageName ; dropTrigger : DROP TRIGGER triggerName ; dropIndex : DROP INDEX indexName ONLINE? FORCE? ((DEFERRED|IMMEDIATE) INVALIDATION)? ; dropView : DROP VIEW viewName (CASCADE CONSTRAINTS)? ; dropEdition : DROP EDITION editionName CASCADE? ; dropOutline : DROP OUTLINE outlineName ; alterOutline : ALTER OUTLINE (PUBLIC | PRIVATE)? outlineName ( REBUILD | RENAME TO outlineName | CHANGE CATEGORY TO categoryName | (ENABLE | DISABLE) )+ ; truncateTable : TRUNCATE TABLE tableName materializedViewLogClause? dropReuseClause? CASCADE? ; createTableSpecification : ((GLOBAL | PRIVATE) TEMPORARY | SHARDED | DUPLICATED)? ; tablespaceClauseWithParen : LP_ tablespaceClause RP_ ; tablespaceClause : TABLESPACE ignoredIdentifier ; createSharingClause : (SHARING EQ_ (METADATA | DATA | EXTENDED DATA | NONE))? ; createDefinitionClause : createRelationalTableClause | createObjectTableClause | createXMLTypeTableClause ; createXMLTypeTableClause : OF? XMLTYPE (LP_ (objectProperties) RP_)? (XMLTYPE xmlTypeStorageClause)? (xmlSchemaSpecClause)? (xmlTypeVirtualColumnsClause)? (ON COMMIT (DELETE | PRESERVE) ROWS)? (oidClause)? (oidIndexClause)? (physicalProperties)? (tableProperties)? ; xmlTypeStorageClause : STORE (AS ( OBJECT RELATIONAL | ((SECUREFILE | BASICFILE)? (CLOB | BINARY XML) (lobSegname (LP_ lobParameters RP_)? | (LP_ lobParameters RP_))?))) | (ALL VARRAYS AS (LOBS | TABLES )) ; xmlSchemaSpecClause : (XMLSCHEMA xmlSchemaURLName)? ELEMENT (elementName | xmlSchemaURLName POUND_ elementName)? (STORE ALL VARRAYS AS (LOBS | TABLES))? ((ALLOW | DISALLOW) NONSCHEMA)? ((ALLOW | DISALLOW) ANYSCHEMA)? ; xmlTypeVirtualColumnsClause : VIRTUAL COLUMNS LP_ (columnName AS LP_ expr RP_ (COMMA_ columnName AS LP_ expr RP_)+) RP_ ; oidClause : OBJECT IDENTIFIER IS (SYSTEM GENERATED | PRIMARY KEY) ; oidIndexClause : OIDINDEX indexName? LP_ (physicalAttributesClause | TABLESPACE tablespaceName)* RP_ ; createRelationalTableClause : (LP_ relationalProperties RP_)? collationClause? commitClause? physicalProperties? tableProperties? ; createMemOptimizeClause : (MEMOPTIMIZE FOR READ)? (MEMOPTIMIZE FOR WRITE)? ; createParentClause : (PARENT tableName)? ; createObjectTableClause : OF objectName objectTableSubstitution? (LP_ objectProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? oidClause? oidIndexClause? physicalProperties? tableProperties? ; relationalProperties : relationalProperty (COMMA_ relationalProperty)* ; relationalProperty : columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint ; columnDefinition : columnName dataType SORT? visibleClause (defaultNullClause expr | identityClause)? (ENCRYPT encryptionSpecification)? (inlineConstraint+ | inlineRefConstraint)? ; visibleClause : (VISIBLE | INVISIBLE)? ; defaultNullClause : DEFAULT (ON NULL)? ; identityClause : GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY identifyOptions ; identifyOptions : LP_? (identityOption+)? RP_? ; identityOption : START WITH (INTEGER_ | LIMIT VALUE) | INCREMENT BY INTEGER_ | MAXVALUE INTEGER_ | NOMAXVALUE | MINVALUE INTEGER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE INTEGER_ | NOCACHE | ORDER | NOORDER ; encryptionSpecification : (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)? ; inlineConstraint : (CONSTRAINT ignoredIdentifier)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState? ; referencesClause : REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))? ; constraintState : notDeferrable | initiallyClause | RELY | NORELY | usingIndexClause | ENABLE | DISABLE | VALIDATE | NOVALIDATE | exceptionsClause ; notDeferrable : NOT? DEFERRABLE ; initiallyClause : INITIALLY (IMMEDIATE | DEFERRED) ; exceptionsClause : EXCEPTIONS INTO tableName ; usingIndexClause : USING INDEX (indexName | createIndexClause)? ; createIndexClause : LP_ createIndex RP_ ; inlineRefConstraint : SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier)? referencesClause constraintState? ; virtualColumnDefinition : columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint* ; outOfLineConstraint : (CONSTRAINT constraintName)? (UNIQUE columnNames | primaryKey columnNames | FOREIGN KEY columnNames referencesClause | CHECK LP_ expr RP_ ) constraintState? ; outOfLineRefConstraint : SCOPE FOR LP_ lobItem RP_ IS tableName | REF LP_ lobItem RP_ WITH ROWID | (CONSTRAINT constraintName)? FOREIGN KEY lobItemList referencesClause constraintState? ; createIndexSpecification : (UNIQUE | BITMAP)? ; clusterIndexClause : CLUSTER clusterName indexAttributes? ; indexAttributes : (ONLINE | (SORT|NOSORT) | REVERSE | (VISIBLE | INVISIBLE)) ; tableIndexClause : tableName alias? indexExpressions ; indexExpressions : LP_? indexExpression (COMMA_ indexExpression)* RP_? ; indexExpression : (columnName | expr) (ASC | DESC)? ; bitmapJoinIndexClause : tableName columnSortsClause_ FROM tableAlias WHERE expr ; columnSortsClause_ : LP_? columnSortClause_ (COMMA_ columnSortClause_)* RP_? ; columnSortClause_ : (tableName | alias)? columnName (ASC | DESC)? ; createIndexDefinitionClause : clusterIndexClause | tableIndexClause | bitmapJoinIndexClause ; tableAlias : tableName alias? (COMMA_ tableName alias?)* ; alterDefinitionClause : (alterTableProperties | columnClauses | constraintClauses | alterTablePartitioning ((DEFERRED| IMMEDIATE) INVALIDATION)? | alterExternalTable)? ; alterTableProperties : renameTableSpecification | REKEY encryptionSpecification ; renameTableSpecification : RENAME TO identifier ; dropSynonym : DROP PUBLIC? SYNONYM (schemaName DOT_)? synonymName FORCE? ; columnClauses : operateColumnClause+ | renameColumnClause ; operateColumnClause : addColumnSpecification | modifyColumnSpecification | dropColumnClause ; addColumnSpecification : ADD LP_ columnOrVirtualDefinitions RP_ columnProperties? ; columnOrVirtualDefinitions : columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* ; columnOrVirtualDefinition : columnDefinition | virtualColumnDefinition ; columnProperties : columnProperty+ ; columnProperty : objectTypeColProperties ; objectTypeColProperties : COLUMN columnName substitutableColumnClause ; substitutableColumnClause : ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS ; modifyColumnSpecification : MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpecification | DECRYPT)? inlineConstraint* ; modifyColSubstitutable : COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE? ; dropColumnClause : SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification ; dropColumnSpecification : DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber? ; columnOrColumnList : (COLUMN columnName) | columnNames ; cascadeOrInvalidate : CASCADE CONSTRAINTS | INVALIDATE ; checkpointNumber : CHECKPOINT NUMBER_ ; renameColumnClause : RENAME COLUMN columnName TO columnName ; constraintClauses : addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+ ; addConstraintSpecification : ADD (outOfLineConstraint+ | outOfLineRefConstraint) ; modifyConstraintClause : MODIFY constraintOption constraintState+ CASCADE? ; constraintWithName : CONSTRAINT constraintName ; constraintOption : constraintWithName | constraintPrimaryOrUnique ; constraintPrimaryOrUnique : primaryKey | UNIQUE columnNames ; renameConstraintClause : RENAME constraintWithName TO ignoredIdentifier ; dropConstraintClause : DROP ( constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT constraintName CASCADE?) ) ; alterExternalTable : (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+ ; objectProperties : ((columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint)?) | outOfLineConstraint | outOfLineRefConstraint | supplementalLoggingProps ; alterIndexInformationClause : rebuildClause ((DEFERRED|IMMEDIATE) | INVALIDATION)? | parallelClause | COMPILE | (ENABLE | DISABLE) | UNUSABLE ONLINE? ((DEFERRED|IMMEDIATE)|INVALIDATION)? | (VISIBLE | INVISIBLE) | renameIndexClause | COALESCE CLEANUP? ONLY? parallelClause? | ((MONITORING | NOMONITORING) USAGE) | UPDATE BLOCK REFERENCES ; renameIndexClause : (RENAME TO indexName)? ; objectTableSubstitution : NOT? SUBSTITUTABLE AT ALL LEVELS ; memOptimizeClause : memOptimizeReadClause? memOptimizeWriteClause? ; memOptimizeReadClause : (MEMOPTIMIZE FOR READ | NO MEMOPTIMIZE FOR READ) ; memOptimizeWriteClause : (MEMOPTIMIZE FOR WRITE | NO MEMOPTIMIZE FOR WRITE) ; enableDisableClauses : (enableDisableClause | enableDisableOthers)? ; enableDisableClause : (ENABLE | DISABLE) (VALIDATE |NO VALIDATE)? ((UNIQUE columnName (COMMA_ columnName)*) | PRIMARY KEY | constraintWithName) usingIndexClause? exceptionsClause? CASCADE? ((KEEP | DROP) INDEX)? ; enableDisableOthers : (ENABLE | DISABLE) (TABLE LOCK | ALL TRIGGERS | CONTAINER_MAP | CONTAINERS_DEFAULT) ; rebuildClause : REBUILD parallelClause? ; parallelClause : NOPARALLEL | PARALLEL NUMBER_? ; usableSpecification : (USABLE | UNUSABLE) ; invalidationSpecification : (DEFERRED | IMMEDIATE) INVALIDATION ; materializedViewLogClause : (PRESERVE | PURGE) MATERIALIZED VIEW LOG ; dropReuseClause : (DROP (ALL)? | REUSE) STORAGE ; collationClause : DEFAULT COLLATION collationName ; createSynonym : CREATE (OR REPLACE)? (EDITIONABLE | NONEDITIONABLE)? (PUBLIC)? SYNONYM (schemaName DOT_)? synonymName (SHARING EQ_ (METADATA | NONE))? FOR objectName (AT_ dbLink)? ; commitClause : (ON COMMIT (DROP | PRESERVE) ROWS)? (ON COMMIT (DELETE | PRESERVE) ROWS)? ; physicalProperties : deferredSegmentCreation? segmentAttributesClause? tableCompression? inmemoryTableClause? ilmClause? | deferredSegmentCreation? (organizationClause?|externalPartitionClause?) | clusterClause ; deferredSegmentCreation : SEGMENT CREATION (IMMEDIATE|DEFERRED) ; segmentAttributesClause : ( physicalAttributesClause | (TABLESPACE tablespaceName | TABLESPACE SET tablespaceSetName) | loggingClause)+ ; physicalAttributesClause : (PCTFREE NUMBER_ | PCTUSED NUMBER_ | INITRANS NUMBER_ | storageClause)+ ; loggingClause : LOGGING | NOLOGGING | FILESYSTEM_LIKE_LOGGING ; storageClause : STORAGE LP_ (INITIAL sizeClause | NEXT sizeClause | MINEXTENTS NUMBER_ | MAXEXTENTS (NUMBER_ | UNLIMITED) | maxsizeClause | PCTINCREASE NUMBER_ | FREELISTS NUMBER_ | FREELIST GROUPS NUMBER_ | OPTIMAL (sizeClause | NULL)? | BUFFER_POOL (KEEP | RECYCLE | DEFAULT) | FLASH_CACHE (KEEP | NONE | DEFAULT) | CELL_FLASH_CACHE (KEEP | NONE | DEFAULT) | ENCRYPT )+ RP_ ; sizeClause : (NUMBER_ | INTEGER_) capacityUnit? ; maxsizeClause : MAXSIZE (UNLIMITED | sizeClause) ; tableCompression : COMPRESS | ROW STORE COMPRESS (BASIC | ADVANCED)? | COLUMN STORE COMPRESS (FOR (QUERY | ARCHIVE) (LOW | HIGH)?)? (NO? ROW LEVEL LOCKING)? | NOCOMPRESS ; inmemoryTableClause : ((INMEMORY inmemoryAttributes?) | NO INMEMORY)? (inmemoryColumnClause)? ; inmemoryAttributes : inmemoryMemcompress? inmemoryPriority? inmemoryDistribute? inmemoryDuplicate? ; inmemoryColumnClause : (INMEMORY inmemoryMemcompress? | NO INMEMORY) columnNames ; inmemoryMemcompress : MEMCOMPRESS FOR ( DML | (QUERY | CAPACITY) (LOW | HIGH)? ) | NO MEMCOMPRESS ; inmemoryPriority : PRIORITY (NONE | LOW | MEDIUM | HIGH | CRITICAL) ; inmemoryDistribute : DISTRIBUTE (AUTO | BY (ROWID RANGE | PARTITION | SUBPARTITION))? (FOR SERVICE (DEFAULT | ALL | serviceName | NONE))? ; inmemoryDuplicate : DUPLICATE | DUPLICATE ALL | NO DUPLICATE ; ilmClause : ILM (ADD POLICY ilmPolicyClause | (DELETE | ENABLE | DISABLE) POLICY ilmPolicyName | (DELETE_ALL | ENABLE_ALL | DISABLE_ALL)) ; ilmPolicyClause : ilmCompressionPolicy | ilmTieringPolicy | ilmInmemoryPolicy ; ilmCompressionPolicy : tableCompression (SEGMENT | GROUP) ( AFTER ilmTimePeriod OF ( NO ACCESS | NO MODIFICATION | CREATION ) | ON functionName) | (ROW STORE COMPRESS ADVANCED | COLUMN STORE COMPRESS FOR QUERY) ROW AFTER ilmTimePeriod OF NO MODIFICATION ; ilmTimePeriod : NUMBER_ ((DAY | DAYS) | (MONTH | MONTHS) | (YEAR | YEARS)) ; ilmTieringPolicy : TIER TO tablespaceName (SEGMENT | GROUP)? (ON functionName)? | TIER TO tablespaceName READ ONLY (SEGMENT | GROUP)? (AFTER ilmTimePeriod OF (NO ACCESS | NO MODIFICATION | CREATION) | ON functionName) ; ilmInmemoryPolicy : (SET INMEMORY inmemoryAttributes | MODIFY INMEMORY inmemoryMemcompress | NO INMEMORY) SEGMENT (AFTER ilmTimePeriod OF (NO ACCESS | NO MODIFICATION | CREATION) | ON functionName) ; organizationClause : ORGANIZATION ( HEAP segmentAttributesClause? heapOrgTableClause | INDEX segmentAttributesClause? indexOrgTableClause | EXTERNAL externalTableClause) ; heapOrgTableClause : tableCompression? inmemoryTableClause? ilmClause? ; indexOrgTableClause : (mappingTableClause | PCTTHRESHOLD NUMBER_ | prefixCompression)* indexOrgOverflowClause? ; externalTableClause : LP_ (TYPE accessDriverType)? (externalTableDataProps)? RP_ (REJECT LIMIT (NUMBER_ | UNLIMITED))? inmemoryTableClause? ; externalTableDataProps : (DEFAULT DIRECTORY directoryName)? (ACCESS PARAMETERS ((opaqueFormatSpec) | USING CLOB subquery))? (LOCATION LP_ (directoryName COLON_)? locationSpecifier (COMMA_ (directoryName COLON_)? locationSpecifier)+ RP_)? ; mappingTableClause : MAPPING TABLE | NOMAPPING ; prefixCompression : COMPRESS NUMBER_? | NOCOMPRESS ; indexOrgOverflowClause : (INCLUDING columnName)? OVERFLOW segmentAttributesClause? ; externalPartitionClause : EXTERNAL PARTITION ATTRIBUTES externalTableClause (REJECT LIMIT)? ; clusterRelatedClause : CLUSTER clusterName columnNames ; tableProperties :columnProperties? readOnlyClause? indexingClause? tablePartitioningClauses? attributeClusteringClause? (CACHE | NOCACHE)? ( RESULT_CACHE ( MODE (DEFAULT | FORCE) ) )? parallelClause? (ROWDEPENDENCIES | NOROWDEPENDENCIES)? enableDisableClause* rowMovementClause? flashbackArchiveClause? (ROW ARCHIVAL)? (AS subquery | FOR EXCHANGE WITH TABLE tableName)? ; readOnlyClause : READ ONLY | READ WRITE ; indexingClause : INDEXING (ON | OFF) ; tablePartitioningClauses : rangePartitions | listPartitions | hashPartitions | compositeRangePartitions | compositeListPartitions | compositeHashPartitions | referencePartitioning | systemPartitioning | consistentHashPartitions | consistentHashWithSubpartitions | partitionsetClauses ; rangePartitions : PARTITION BY RANGE columnNames (INTERVAL LP_ expr RP_ (STORE IN LP_ tablespaceName (COMMA_ tablespaceName)* RP_)?)? LP_ PARTITION partitionName? rangeValuesClause tablePartitionDescription (COMMA_ PARTITION partitionName? rangeValuesClause tablePartitionDescription externalPartSubpartDataProps?)* RP_ ; rangeValuesClause : VALUES LESS THAN LP_? (numberLiterals | MAXVALUE) (COMMA_ (numberLiterals | MAXVALUE))* RP_? ; tablePartitionDescription : (INTERNAL | EXTERNAL)? deferredSegmentCreation? readOnlyClause? indexingClause? segmentAttributesClause? (tableCompression | prefixCompression)? inmemoryClause? ilmClause? (OVERFLOW segmentAttributesClause?)? (lobStorageClause | varrayColProperties | nestedTableColProperties)* ; inmemoryClause : INMEMORY inmemoryAttributes? | NO INMEMORY ; varrayColProperties : VARRAY varrayItem (substitutableColumnClause? varrayStorageClause | substitutableColumnClause) ; nestedTableColProperties : NESTED TABLE (nestedItem | COLUMN_VALUE) substitutableColumnClause? (LOCAL | GLOBAL)? STORE AS storageTable LP_ (LP_ objectProperties RP_ | physicalProperties | columnProperties) RP_ (RETURN AS? (LOCATOR | VALUE))? ; lobStorageClause : LOB ( LP_ lobItem (COMMA_ lobItem)* RP_ STORE AS ((SECUREFILE | BASICFILE) | LP_ lobStorageParameters RP_)+ | LP_ lobItem RP_ STORE AS ((SECUREFILE | BASICFILE) | lobSegname | LP_ lobStorageParameters RP_)+ ) ; varrayStorageClause : STORE AS (SECUREFILE | BASICFILE)? LOB (lobSegname? LP_ lobStorageParameters RP_ | lobSegname) ; lobStorageParameters : ((TABLESPACE tablespaceName | TABLESPACE SET tablespaceSetName) | lobParameters storageClause?)+ | storageClause ; lobParameters : ( (ENABLE | DISABLE) STORAGE IN ROW | CHUNK NUMBER_ | PCTVERSION NUMBER_ | FREEPOOLS NUMBER_ | lobRetentionClause | lobDeduplicateClause | lobCompressionClause | (ENCRYPT encryptionSpecification | DECRYPT) | (CACHE | NOCACHE | CACHE READS) loggingClause? )+ ; lobRetentionClause : RETENTION (MAX | MIN NUMBER_ | AUTO | NONE)? ; lobDeduplicateClause : DEDUPLICATE | KEEP_DUPLICATES ; lobCompressionClause : (COMPRESS (HIGH | MEDIUM | LOW)? | NOCOMPRESS) ; externalPartSubpartDataProps : (DEFAULT DIRECTORY directoryName) (LOCATION LP_ (directoryName COLON_)? locationSpecifier (COMMA_ (directoryName COLON_)? locationSpecifier)* RP_)? ; listPartitions : PARTITION BY LIST columnNames (AUTOMATIC (STORE IN LP_? tablespaceName (COMMA_ tablespaceName)* RP_?))? LP_ PARTITION partitionName? listValuesClause tablePartitionDescription (COMMA_ PARTITION partitionName? listValuesClause tablePartitionDescription externalPartSubpartDataProps?)* RP_ ; listValuesClause : VALUES ( listValues | DEFAULT ) ; listValues : (literals | NULL) (COMMA_ (literals | NULL))* | (LP_? ( (literals | NULL) (COMMA_ (literals | NULL))* ) RP_?) (COMMA_ LP_? ( (literals | NULL) (COMMA_ (literals | NULL))* ) RP_?)* ; hashPartitions : PARTITION BY HASH columnNames (individualHashPartitions | hashPartitionsByQuantity) ; hashPartitionsByQuantity : PARTITIONS INTEGER_ (STORE IN (tablespaceName (COMMA_ tablespaceName)*))? (tableCompression | indexCompression)? (OVERFLOW STORE IN (tablespaceName (COMMA_ tablespaceName)*))? ; indexCompression : prefixCompression | advancedIndexCompression ; advancedIndexCompression : COMPRESS ADVANCED (LOW | HIGH)? | NOCOMPRESS ; individualHashPartitions : LP_? (PARTITION partitionName? readOnlyClause? indexingClause? partitioningStorageClause?) (COMMA_ PARTITION partitionName? readOnlyClause? indexingClause? partitioningStorageClause?)* RP_? ; partitioningStorageClause : ((TABLESPACE tablespaceName | TABLESPACE SET tablespaceSetName) | OVERFLOW (TABLESPACE tablespaceName | TABLESPACE SET tablespaceSetName)? | tableCompression | indexCompression | inmemoryClause | ilmClause | lobPartitioningStorage | VARRAY varrayItem STORE AS (SECUREFILE | BASICFILE)? LOB lobSegname )* ; lobPartitioningStorage :LOB LP_ lobItem RP_ STORE AS (BASICFILE | SECUREFILE)? (lobSegname (LP_ TABLESPACE tablespaceName | TABLESPACE SET tablespaceSetName RP_)? | LP_ TABLESPACE tablespaceName | TABLESPACE SET tablespaceSetName RP_ )? ; compositeRangePartitions : PARTITION BY RANGE columnNames (INTERVAL LP_ expr RP_ (STORE IN LP_? tablespaceName (COMMA_ tablespaceName)* RP_?)?)? (subpartitionByRange | subpartitionByList | subpartitionByHash) LP_? rangePartitionDesc (COMMA_ rangePartitionDesc)* RP_? ; subpartitionByRange : SUBPARTITION BY RANGE columnNames subpartitionTemplate? ; subpartitionByList : SUBPARTITION BY LIST columnNames subpartitionTemplate? ; subpartitionByHash : SUBPARTITION BY HASH columnNames (SUBPARTITIONS NUMBER_ (STORE IN LP_ tablespaceName (COMMA_ tablespaceName)? RP_)? | subpartitionTemplate)? ; subpartitionTemplate : SUBPARTITION TEMPLATE (LP_? rangeSubpartitionDesc (COMMA_ rangeSubpartitionDesc)* | listSubpartitionDesc (COMMA_ listSubpartitionDesc)* | individualHashSubparts (COMMA_ individualHashSubparts)* RP_?) | hashSubpartitionQuantity ; rangeSubpartitionDesc : SUBPARTITION subpartitionName? rangeValuesClause readOnlyClause? indexingClause? partitioningStorageClause? externalPartSubpartDataProps? ; listSubpartitionDesc : SUBPARTITION subpartitionName? listValuesClause readOnlyClause? indexingClause? partitioningStorageClause? externalPartSubpartDataProps? ; individualHashSubparts : SUBPARTITION subpartitionName? readOnlyClause? indexingClause? partitioningStorageClause? ; rangePartitionDesc : PARTITION partitionName? rangeValuesClause tablePartitionDescription ((LP_? rangeSubpartitionDesc (COMMA_ rangeSubpartitionDesc)* | listSubpartitionDesc (COMMA_ listSubpartitionDesc)* | individualHashSubparts (COMMA_ individualHashSubparts)* RP_?) | hashSubpartitionQuantity)? ; compositeListPartitions : PARTITION BY LIST columnNames (AUTOMATIC (STORE IN LP_? tablespaceName (COMMA_ tablespaceName)* RP_?)?)? (subpartitionByRange | subpartitionByList | subpartitionByHash) LP_? listPartitionDesc (COMMA_ listPartitionDesc)* RP_? ; listPartitionDesc : PARTITIONSET partitionSetName listValuesClause (TABLESPACE SET tablespaceSetName)? lobStorageClause? (SUBPARTITIONS STORE IN LP_? tablespaceSetName (COMMA_ tablespaceSetName)* RP_?)? ; compositeHashPartitions : PARTITION BY HASH columnNames (subpartitionByRange | subpartitionByList | subpartitionByHash) (individualHashPartitions | hashPartitionsByQuantity) ; referencePartitioning :PARTITION BY REFERENCE LP_ constraint RP_ (LP_? referencePartitionDesc (COMMA_ referencePartitionDesc)* RP_?)? ; referencePartitionDesc : PARTITION partitionName? tablePartitionDescription? ; constraint : inlineConstraint | outOfLineConstraint | inlineRefConstraint | outOfLineRefConstraint ; systemPartitioning : PARTITION BY SYSTEM (PARTITIONS NUMBER_ | referencePartitionDesc (COMMA_ referencePartitionDesc)*)? ; consistentHashPartitions : PARTITION BY CONSISTENT HASH columnNames (PARTITIONS AUTO)? TABLESPACE SET tablespaceSetName ; consistentHashWithSubpartitions : PARTITION BY CONSISTENT HASH columnNames (subpartitionByRange | subpartitionByList | subpartitionByHash) (PARTITIONS AUTO)? ; partitionsetClauses : rangePartitionsetClause | listPartitionsetClause ; rangePartitionsetClause : PARTITIONSET BY RANGE columnNames PARTITION BY CONSISTENT HASH columnNames (SUBPARTITION BY ((RANGE | HASH) columnNames | LIST LP_ columnName LP_) subpartitionTemplate?)? PARTITIONS AUTO LP_ rangePartitionsetDesc (COMMA_ rangePartitionsetDesc)* RP_ ; rangePartitionsetDesc : PARTITIONSET partitionSetName rangeValuesClause (TABLESPACE SET tablespaceSetName)? (lobStorageClause)? (SUBPARTITIONS STORE IN tablespaceSetName?)? ; listPartitionsetClause : PARTITIONSET BY RANGE LP_ columnName RP_ PARTITION BY CONSISTENT HASH columnNames (SUBPARTITION BY ((RANGE | HASH) columnNames | LIST LP_ columnName LP_) subpartitionTemplate?)? PARTITIONS AUTO LP_ rangePartitionsetDesc (COMMA_ rangePartitionsetDesc)* RP_ ; attributeClusteringClause : CLUSTERING clusteringJoin? clusterClause clusteringWhen? zonemapClause? ; clusteringJoin : tableName (JOIN tableName ON LP_ expr RP_)+ ; clusterClause : BY (LINEAR | INTERLEAVED)? ORDER clusteringColumns ; createDirectory : CREATE (OR REPLACE)? DIRECTORY directoryName (SHARING EQ_ (METADATA | NONE))? AS pathString ; clusteringColumns : LP_? clusteringColumnGroup (COMMA_ clusteringColumnGroup)* RP_? ; clusteringColumnGroup : columnNames ; clusteringWhen : ((YES | NO) ON LOAD)? ((YES | NO) ON DATA MOVEMENT)? ; zonemapClause : (WITH MATERIALIZED ZONEMAP (LP_ zonemapName RP_)?) | (WITHOUT MATERIALIZED ZONEMAP) ; rowMovementClause : (ENABLE | DISABLE) ROW MOVEMENT ; flashbackArchiveClause : FLASHBACK ARCHIVE flashbackArchiveName? | NO FLASHBACK ARCHIVE ; alterPackage : ALTER PACKAGE packageName ( | packageCompileClause | (EDITIONABLE | NONEDITIONABLE) ) ; packageCompileClause : COMPILE DEBUG? (PACKAGE | SPECIFICATION | BODY)? (compilerParametersClause*)? (REUSE SETTINGS)? ; alterSynonym : ALTER PUBLIC? SYNONYM (schemaName DOT_)? synonymName (COMPILE | EDITIONABLE | NONEDITIONABLE) ; alterTablePartitioning : modifyTablePartition | moveTablePartition | addTablePartition | coalesceTablePartition | dropTablePartition ; modifyTablePartition : modifyRangePartition | modifyHashPartition | modifyListPartition ; modifyRangePartition : MODIFY partitionExtendedName (partitionAttributes | (addRangeSubpartition | addHashSubpartition | addListSubpartition) | coalesceTableSubpartition | alterMappingTableClauses | REBUILD? UNUSABLE LOCAL INDEXES | readOnlyClause | indexingClause) ; modifyHashPartition : MODIFY partitionExtendedName (partitionAttributes | coalesceTableSubpartition | alterMappingTableClauses | REBUILD? UNUSABLE LOCAL INDEXES | readOnlyClause | indexingClause) ; modifyListPartition : MODIFY partitionExtendedName (partitionAttributes | (ADD | DROP) VALUES LP_ listValues RP_ | (addRangeSubpartition | addHashSubpartition | addListSubpartition) | coalesceTableSubpartition | REBUILD? UNUSABLE LOCAL INDEXES | readOnlyClause | indexingClause) ; partitionExtendedName : PARTITION partitionName | PARTITION FOR LP_ partitionKeyValue (COMMA_ partitionKeyValue)* RP_ ; addRangeSubpartition : ADD rangeSubpartitionDesc (COMMA_ rangeSubpartitionDesc)* dependentTablesClause? updateIndexClauses? ; dependentTablesClause : DEPENDENT TABLES LP_ tableName LP_ partitionSpec (COMMA_ partitionSpec)* RP_ (COMMA_ tableName LP_ partitionSpec (COMMA_ partitionSpec)* RP_)* RP_ ; addHashSubpartition : ADD individualHashSubparts dependentTablesClause? updateIndexClauses? parallelClause? ; addListSubpartition : ADD listSubpartitionDesc (COMMA_ listSubpartitionDesc)* dependentTablesClause? updateIndexClauses? ; coalesceTableSubpartition : COALESCE SUBPARTITION subpartitionName updateIndexClauses? parallelClause? allowDisallowClustering? ; allowDisallowClustering : (ALLOW | DISALLOW) CLUSTERING ; alterMappingTableClauses : MAPPING TABLE (allocateExtentClause | deallocateUnusedClause) ; alterView : ALTER VIEW viewName ( | ADD outOfLineConstraint | MODIFY CONSTRAINT constraintName (RELY | NORELY) | DROP (CONSTRAINT constraintName | PRIMARY KEY | UNIQUE columnNames) | COMPILE | READ (ONLY | WRITE) | (EDITIONABLE | NONEDITIONABLE) ) ; deallocateUnusedClause : DEALLOCATE UNUSED (KEEP sizeClause)? ; allocateExtentClause : ALLOCATE EXTENT (LP_ (SIZE sizeClause | DATAFILE SQ_ fileName SQ_ | INSTANCE NUMBER_)* RP_)? ; partitionSpec : PARTITION partitionName? tablePartitionDescription? ; partitionAttributes : (physicalAttributesClause | loggingClause | allocateExtentClause | deallocateUnusedClause | shrinkClause)* (OVERFLOW (physicalAttributesClause | loggingClause | allocateExtentClause | deallocateUnusedClause)*)? tableCompression? inmemoryClause? ; shrinkClause : SHRINK SPACE COMPACT? CASCADE? ; moveTablePartition : MOVE partitionExtendedName (MAPPING TABLE)? tablePartitionDescription? filterCondition? updateAllIndexesClause? parallelClause? allowDisallowClustering? ONLINE? ; filterCondition : INCLUDING ROWS whereClause ; whereClause : WHERE expr ; coalesceTablePartition : COALESCE PARTITION updateIndexClauses? parallelClause? allowDisallowClustering? ; addTablePartition : ADD ((PARTITION partitionName? addRangePartitionClause (COMMA_ PARTITION partitionName? addRangePartitionClause)*) | (PARTITION partitionName? addListPartitionClause (COMMA_ PARTITION partitionName? addListPartitionClause)*) | (PARTITION partitionName? addSystemPartitionClause (COMMA_ PARTITION partitionName? addSystemPartitionClause)*) (BEFORE (partitionName | NUMBER_))? | (PARTITION partitionName? addHashPartitionClause) ) dependentTablesClause? ; addRangePartitionClause : rangeValuesClause tablePartitionDescription? externalPartSubpartDataProps? ((LP_? (rangeSubpartitionDesc (COMMA_ rangeSubpartitionDesc)* | listSubpartitionDesc (COMMA_ listSubpartitionDesc)* | individualHashSubparts (COMMA_ individualHashSubparts)*) RP_?) | hashSubpartsByQuantity)? updateIndexClauses? ; addListPartitionClause : listValuesClause tablePartitionDescription? externalPartSubpartDataProps? ((LP_? (rangeSubpartitionDesc (COMMA_ rangeSubpartitionDesc)* | listSubpartitionDesc (COMMA_ listSubpartitionDesc)* | individualHashSubparts (COMMA_ individualHashSubparts)*) RP_?) | hashSubpartsByQuantity)? updateIndexClauses? ; hashSubpartsByQuantity : SUBPARTITIONS NUMBER_ (STORE IN LP_ tablespaceName (COMMA_ tablespaceName)* RP_)? ; addSystemPartitionClause : tablePartitionDescription? updateIndexClauses? ; addHashPartitionClause : partitioningStorageClause updateIndexClauses? parallelClause? readOnlyClause? indexingClause? ; dropTablePartition : DROP partitionExtendedNames (updateIndexClauses parallelClause?)? ; partitionExtendedNames : (PARTITION | PARTITIONS) (partitionName | partitionForClauses) (COMMA_ (partitionName | partitionForClauses))* ; partitionForClauses : FOR LP_ partitionKeyValue (COMMA_ partitionKeyValue)* RP_ ; updateIndexClauses : updateGlobalIndexClause | updateAllIndexesClause ; updateGlobalIndexClause : (UPDATE | INVALIDATE) GLOBAL INDEXES ; updateAllIndexesClause : UPDATE INDEXES (LP_ indexName LP_ (updateIndexPartition | updateIndexSubpartition) RP_ (COMMA_ indexName LP_ (updateIndexPartition | updateIndexSubpartition) RP_)* RP_)? ; updateIndexPartition : indexPartitionDesc indexSubpartitionClause? (COMMA_ indexPartitionDesc indexSubpartitionClause?)* ; indexPartitionDesc : PARTITION (partitionName ((segmentAttributesClause | indexCompression)+ | PARAMETERS LP_ SQ_ odciParameters SQ_ RP_ )? usableSpecification? )? ; indexSubpartitionClause : STORE IN LP_ tablespaceName (COMMA_ tablespaceName)* RP_ | LP_ SUBPARTITION subpartitionName? (TABLESPACE tablespaceName)? indexCompression? usableSpecification? (COMMA_ SUBPARTITION subpartitionName? (TABLESPACE tablespaceName)? indexCompression? usableSpecification?)* RP_ ; updateIndexSubpartition : SUBPARTITION subpartitionName? (TABLESPACE tablespaceName)? (COMMA_ SUBPARTITION subpartitionName? (TABLESPACE tablespaceName)?)* ; supplementalLoggingProps : SUPPLEMENTAL LOG supplementalLogGrpClause|supplementalIdKeyClause ; supplementalLogGrpClause : GROUP logGroupName LP_ columnName (NO LOG)? (COMMA_ columnName (NO LOG)?)* RP_ ALWAYS? ; supplementalIdKeyClause : DATA LP_ (ALL | PRIMARY KEY | UNIQUE | FOREIGN KEY) (COMMA_ (ALL | PRIMARY KEY | UNIQUE | FOREIGN KEY))* RP_ COLUMNS ; alterSession : ALTER SESSION alterSessionOption ; alterSessionOption : adviseClause | closeDatabaseLinkClause | commitInProcedureClause | securiyClause | parallelExecutionClause | resumableClause | shardDdlClause | syncWithPrimaryClause | alterSessionSetClause ; adviseClause : ADVISE (COMMIT | ROLLBACK | NOTHING) ; closeDatabaseLinkClause : CLOSE DATABASE LINK dbLink ; commitInProcedureClause : (ENABLE | DISABLE) COMMIT IN PROCEDURE ; securiyClause : (ENABLE | DISABLE) GUARD ; parallelExecutionClause : (ENABLE | DISABLE | FORCE) PARALLEL (DML | DDL | QUERY) (PARALLEL numberLiterals)? ; resumableClause : enableResumableClause | disableResumableClause ; enableResumableClause : ENABLE RESUMABLE (TIMEOUT numberLiterals)? (NAME stringLiterals)? ; disableResumableClause : DISABLE RESUMABLE ; shardDdlClause : (ENABLE | DISABLE) SHARD DDL ; syncWithPrimaryClause : SYNC WITH PRIMARY ; alterSessionSetClause : SET alterSessionSetClauseOption ; alterSessionSetClauseOption : parameterClause | editionClause | containerClause | rowArchivalVisibilityClause | defaultCollationClause ; parameterClause : (parameterName EQ_ parameterValue)+ ; editionClause : EDITION EQ_ editionName ; containerClause : CONTAINER EQ_ containerName (SERVICE EQ_ serviceName)? ; rowArchivalVisibilityClause : ROW ARCHIVAL VISIBILITY EQ_ (ACTIVE | ALL) ; defaultCollationClause : DEFAULT_COLLATION EQ_ (collationName | NONE) ; alterDatabaseDictionary : ALTER DATABASE DICTIONARY ( | ENCRYPT CREDENTIALS | REKEY CREDENTIALS | DELETE CREDENTIALS KEY ) ; alterDatabase : ALTER databaseClauses ( startupClauses | recoveryClauses | databaseFileClauses | logfileClauses | controlfileClauses | standbyDatabaseClauses | defaultSettingsClauses | instanceClauses | securityClause | prepareClause | dropMirrorCopy | lostWriteProtection | cdbFleetClauses | propertyClause ) ; databaseClauses : DATABASE databaseName | PLUGGABLE DATABASE pdbName ; startupClauses : MOUNT ((STANDBY | CLONE) DATABASE)? | OPEN ((READ WRITE)? (RESETLOGS | NORESETLOGS)? (UPGRADE | DOWNGRADE)? | READ ONLY) ; recoveryClauses : generalRecovery | managedStandbyRecovery | BEGIN BACKUP | END BACKUP ; generalRecovery : RECOVER (AUTOMATIC)? (FROM locationName)? ( (fullDatabaseRecovery | partialDatabaseRecovery | LOGFILE fileName) ((TEST | ALLOW NUMBER_ CORRUPTION | parallelClause)+)? | CONTINUE DEFAULT? | CANCEL ) ; fullDatabaseRecovery : STANDBY? DATABASE ((UNTIL (CANCEL | TIME dateValue | CHANGE NUMBER_ | CONSISTENT) | USING BACKUP CONTROLFILE | SNAPSHOT TIME dateValue )+)? ; partialDatabaseRecovery : TABLESPACE tablespaceName (COMMA_ tablespaceName)* | DATAFILE (fileName | fileNumber) (COMMA_ (fileName | fileNumber))* ; managedStandbyRecovery : RECOVER (MANAGED STANDBY DATABASE ((USING ARCHIVED LOGFILE | DISCONNECT (FROM SESSION)? | NODELAY | UNTIL CHANGE NUMBER_ | UNTIL CONSISTENT | USING INSTANCES (ALL | NUMBER_) | parallelClause)+ | FINISH | CANCEL)? | TO LOGICAL STANDBY (databaseName | KEEP IDENTITY)) ; databaseFileClauses : RENAME FILE fileName (COMMA_ fileName)* TO fileName | createDatafileClause | alterDatafileClause | alterTempfileClause | moveDatafileClause ; createDatafileClause : CREATE DATAFILE (fileName | fileNumber) (COMMA_ (fileName | fileNumber))* ( AS (fileSpecifications | NEW))? ; fileSpecifications : fileSpecification (COMMA_ fileSpecification)* ; fileSpecification : datafileTempfileSpec | redoLogFileSpec ; datafileTempfileSpec : (fileName | asmFileName )? (SIZE sizeClause)? REUSE? autoextendClause? ; autoextendClause : AUTOEXTEND (OFF | ON (NEXT sizeClause)? maxsizeClause?) ; redoLogFileSpec : ((fileName | asmFileName) | LP_ (fileName | asmFileName) (COMMA_ (fileName | asmFileName))* RP_)? (SIZE sizeClause)? (BLOCKSIZE sizeClause)? REUSE? ; alterDatafileClause : DATAFILE (fileName | NUMBER_) (COMMA_ (fileName | NUMBER_))* (ONLINE | OFFLINE (FOR DROP)? | RESIZE sizeClause | autoextendClause | END BACKUP | ENCRYPT | DECRYPT) ; alterTempfileClause : TEMPFILE (fileName | NUMBER_) (COMMA_ (fileName | NUMBER_))* (RESIZE sizeClause | autoextendClause | DROP (INCLUDING DATAFILES)? | ONLINE | OFFLINE) ; logfileClauses : ((ARCHIVELOG MANUAL? | NOARCHIVELOG ) | NO? FORCE LOGGING | SET STANDBY NOLOGGING FOR (DATA AVAILABILITY | LOAD PERFORMANCE) | RENAME FILE fileName (COMMA_ fileName)* TO fileName | CLEAR UNARCHIVED? LOGFILE logfileDescriptor (COMMA_ logfileDescriptor)* (UNRECOVERABLE DATAFILE)? | addLogfileClauses | dropLogfileClauses | switchLogfileClause | supplementalDbLogging) ; logfileDescriptor : GROUP NUMBER_ | LP_ fileName (COMMA_ fileName)* RP_ | fileName ; addLogfileClauses : ADD STANDBY? LOGFILE (((INSTANCE instanceName)? | (THREAD SQ_ NUMBER_ SQ_)?) (GROUP NUMBER_)? redoLogFileSpec (COMMA_ (GROUP NUMBER_)? redoLogFileSpec)* | MEMBER fileName REUSE? (COMMA_ fileName REUSE?)* TO logfileDescriptor (COMMA_ logfileDescriptor)*) ; controlfileClauses : CREATE ((LOGICAL | PHYSICAL)? STANDBY | FAR SYNC INSTANCE) CONTROLFILE AS fileName REUSE? | BACKUP CONTROLFILE TO (fileName REUSE? | traceFileClause) ; traceFileClause : TRACE (AS fileName REUSE?)? (RESETLOGS | NORESETLOGS)? ; dropLogfileClauses : DROP STANDBY? LOGFILE (logfileDescriptor (COMMA_ logfileDescriptor)* | MEMBER fileName (COMMA_ fileName)*) ; switchLogfileClause : SWITCH ALL LOGFILES TO BLOCKSIZE NUMBER_ ; supplementalDbLogging : (ADD | DROP) SUPPLEMENTAL LOG ( DATA | supplementalIdKeyClause | supplementalPlsqlClause | supplementalSubsetReplicationClause) ; supplementalPlsqlClause : DATA FOR PROCEDURAL REPLICATION ; supplementalSubsetReplicationClause : DATA SUBSET DATABASE REPLICATION ; standbyDatabaseClauses : ((activateStandbyDbClause | maximizeStandbyDbClause | registerLogfileClause | commitSwitchoverClause | startStandbyClause | stopStandbyClause | convertDatabaseClause) parallelClause?) | (switchoverClause | failoverClause) ; activateStandbyDbClause : ACTIVATE (PHYSICAL | LOGICAL)? STANDBY DATABASE (FINISH APPLY)? ; maximizeStandbyDbClause : SET STANDBY DATABASE TO MAXIMIZE (PROTECTION | AVAILABILITY | PERFORMANCE) ; registerLogfileClause : REGISTER (OR REPLACE)? (PHYSICAL | LOGICAL)? LOGFILE fileSpecifications (FOR logminerSessionName)? ; commitSwitchoverClause : (PREPARE | COMMIT) TO SWITCHOVER ( TO (((PHYSICAL | LOGICAL)? PRIMARY | PHYSICAL? STANDBY) ((WITH | WITHOUT) SESSION SHUTDOWN (WAIT | NOWAIT))? | LOGICAL STANDBY) | CANCEL )? ; startStandbyClause : START LOGICAL STANDBY APPLY IMMEDIATE? NODELAY? (NEW PRIMARY dbLink | INITIAL scnValue? | (SKIP_SYMBOL FAILED TRANSACTION | FINISH))? ; stopStandbyClause : (STOP | ABORT) LOGICAL STANDBY APPLY ; switchoverClause : SWITCHOVER TO databaseName (VERIFY | FORCE)? ; convertDatabaseClause : CONVERT TO (PHYSICAL | SNAPSHOT) STANDBY ; failoverClause : FAILOVER TO databaseName FORCE? ; defaultSettingsClauses : DEFAULT EDITION EQ_ editionName | SET DEFAULT bigOrSmallFiles TABLESPACE | DEFAULT TABLESPACE tablespaceName | DEFAULT LOCAL? TEMPORARY TABLESPACE (tablespaceName | tablespaceGroupName) | RENAME GLOBAL_NAME TO databaseName DOT_ domain (DOT_ domain)* | ENABLE BLOCK CHANGE TRACKING (USING FILE fileName REUSE?)? | DISABLE BLOCK CHANGE TRACKING | NO? FORCE FULL DATABASE CACHING | CONTAINERS DEFAULT TARGET EQ_ (LP_ containerName RP_ | NONE) | flashbackModeClause | undoModeClause | setTimeZoneClause ; setTimeZoneClause : SET TIME_ZONE EQ_ ((PLUS_ | MINUS_) dateValue | timeZoneRegion) ; timeZoneRegion : STRING_ ; flashbackModeClause : FLASHBACK (ON | OFF) ; undoModeClause : LOCAL UNDO (ON | OFF) ; moveDatafileClause : MOVE DATAFILE LP_ (fileName | asmFileName | fileNumber) RP_ (TO LP_ (fileName | asmFileName) RP_ )? REUSE? KEEP? ; instanceClauses : (ENABLE | DISABLE) INSTANCE instanceName ; securityClause : GUARD (ALL | STANDBY | NONE) ; prepareClause : PREPARE MIRROR COPY copyName (WITH (UNPROTECTED | MIRROR | HIGH) REDUNDANCY)? ; dropMirrorCopy : DROP MIRROR COPY mirrorName ; lostWriteProtection : (ENABLE | DISABLE | REMOVE | SUSPEND)? LOST WRITE PROTECTION ; cdbFleetClauses : leadCdbClause | leadCdbUriClause ; leadCdbClause : SET LEAD_CDB EQ_ (TRUE | FALSE) ; leadCdbUriClause : SET LEAD_CDB_URI EQ_ uriString ; propertyClause : PROPERTY (SET | REMOVE) DEFAULT_CREDENTIAL EQ_ qualifiedCredentialName ; alterSystem : ALTER SYSTEM alterSystemOption ; alterSystemOption : archiveLogClause | checkpointClause | checkDatafilesClause | distributedRecovClauses | flushClause | endSessionClauses | alterSystemSwitchLogfileClause | suspendResumeClause | quiesceClauses | rollingMigrationClauses | rollingPatchClauses | alterSystemSecurityClauses | affinityClauses | shutdownDispatcherClause | registerClause | setClause | resetClause | relocateClientClause | cancelSqlClause | flushPasswordfileMetadataCacheClause ; archiveLogClause : ARCHIVE LOG instanceClause? (sequenceClause | changeClause | currentClause | groupClause | logfileClause | nextClause | allClause) toLocationClause? ; checkpointClause : CHECKPOINT (GLOBAL | LOCAL)? ; checkDatafilesClause : CHECK DATAFILES (GLOBAL | LOCAL)? ; distributedRecovClauses : (ENABLE | DISABLE) DISTRIBUTED RECOVERY ; flushClause : FLUSH flushClauseOption ; endSessionClauses : (disconnectSessionClause | killSessionClause) (IMMEDIATE | NOREPLY)? ; alterSystemSwitchLogfileClause : SWITCH LOGFILE ; suspendResumeClause : SUSPEND | RESUME ; quiesceClauses : QUIESCE RESTRICTED | UNQUIESCE ; rollingMigrationClauses : startRollingMigrationClause | stopRollingMigrationClause ; rollingPatchClauses : startRollingPatchClause | stopRollingPatchClause ; alterSystemSecurityClauses : restrictedSessionClause | setEncryptionWalletOpenClause | setEncryptionWalletCloseClause | setEncryptionKeyClause ; affinityClauses : enableAffinityClause | disableAffinityClause ; shutdownDispatcherClause : SHUTDOWN IMMEDIATE? dispatcherName ; registerClause : REGISTER ; setClause : SET alterSystemSetClause+ ; resetClause : RESET alterSystemResetClause+ ; relocateClientClause : RELOCATE CLIENT clientId ; cancelSqlClause : CANCEL SQL SQ_ sessionId serialNumber (AT_ instanceId)? sqlId? SQ_ ; flushPasswordfileMetadataCacheClause : FLUSH PASSWORDFILE_METADATA_CACHE ; instanceClause : INSTANCE instanceName ; sequenceClause : SEQUENCE INTEGER_ ; changeClause : CHANGE INTEGER_ ; currentClause : CURRENT NOSWITCH? ; groupClause : GROUP INTEGER_ ; logfileClause : LOGFILE logFileName (USING BACKUP CONTROLFILE)? ; nextClause : NEXT ; allClause : ALL ; toLocationClause : TO logFileGroupsArchivedLocationName ; flushClauseOption : sharedPoolClause | globalContextClause | bufferCacheClause | flashCacheClause | redoToClause ; disconnectSessionClause : DISCONNECT SESSION SQ_ INTEGER_ COMMA_ INTEGER_ SQ_ POST_TRANSACTION? ; killSessionClause : KILL SESSION SQ_ INTEGER_ COMMA_ INTEGER_ (COMMA_ AT_ INTEGER_)? SQ_ ; startRollingMigrationClause : START ROLLING MIGRATION TO asmVersion ; stopRollingMigrationClause : STOP ROLLING MIGRATION ; startRollingPatchClause : START ROLLING PATCH ; stopRollingPatchClause : STOP ROLLING PATCH ; restrictedSessionClause : (ENABLE | DISABLE) RESTRICTED SESSION ; setEncryptionWalletOpenClause : SET ENCRYPTION WALLET OPEN IDENTIFIED BY (walletPassword | hsmAuthString) ; setEncryptionWalletCloseClause : SET ENCRYPTION WALLET CLOSE (IDENTIFIED BY (walletPassword | hsmAuthString))? ; setEncryptionKeyClause : SET ENCRYPTION KEY (identifiedByWalletPassword | identifiedByHsmAuthString) ; enableAffinityClause : ENABLE AFFINITY tableName (SERVICE serviceName)? ; disableAffinityClause : DISABLE AFFINITY tableName ; alterSystemSetClause : setParameterClause | useStoredOutlinesClause | globalTopicEnabledClause ; alterSystemResetClause : parameterName scopeClause* ; sharedPoolClause : SHARED_POOL ; globalContextClause : GLOBAL CONTEXT ; bufferCacheClause : BUFFER_CACHE ; flashCacheClause : FLASH_CACHE ; redoToClause : REDO TO targetDbName (NO? CONFIRM APPLY)? ; identifiedByWalletPassword : certificateId? IDENTIFIED BY walletPassword ; identifiedByHsmAuthString : IDENTIFIED BY hsmAuthString (MIGRATE USING walletPassword)? ; setParameterClause : parameterName EQ_ parameterValue (COMMA_ parameterValue)* alterSystemCommentClause? DEFERRED? containerCurrentAllClause? scopeClause* ; useStoredOutlinesClause : USE_STORED_OUTLINES EQ_ (TRUE | FALSE | categoryName) ; globalTopicEnabledClause : GLOBAL_TOPIC_ENABLED EQ_ (TRUE | FALSE) ; alterSystemCommentClause : COMMENT EQ_ stringLiterals ; containerCurrentAllClause : CONTAINER EQ_ (CURRENT | ALL) ; scopeClause : SCOPE EQ_ (MEMORY | SPFILE | BOTH) | SID EQ_ (SQ_ sessionId SQ_ | SQ_ ASTERISK_ SQ_) ; analyze : (ANALYZE ((TABLE tableName| INDEX indexName) partitionExtensionClause? | CLUSTER clusterName)) (validationClauses | LIST CHAINED ROWS intoClause? | DELETE SYSTEM? STATISTICS) ; partitionExtensionClause : PARTITION (LP_ partitionName RP_ | FOR LP_ partitionKeyValue (COMMA_ partitionKeyValue) RP_) | SUBPARTITION (LP_ subpartitionName RP_ | FOR LP_ subpartitionKeyValue (COMMA_ subpartitionKeyValue) RP_) ; validationClauses : VALIDATE REF UPDATE (SET DANGLING TO NULL)? | VALIDATE STRUCTURE (CASCADE (FAST | COMPLETE (OFFLINE | ONLINE) intoClause?))? ; intoClause : INTO tableName ; associateStatistics : ASSOCIATE STATISTICS WITH (columnAssociation | functionAssociation) storageTableClause? ; columnAssociation : COLUMNS tableName DOT_ columnName (COMMA_ tableName DOT_ columnName)* usingStatisticsType ; functionAssociation : (FUNCTIONS function (COMMA_ function)* | PACKAGES packageName (COMMA_ packageName)* | TYPES typeName (COMMA_ typeName)* | INDEXES indexName (COMMA_ indexName)* | INDEXTYPES indextypeName (COMMA_ indextypeName)*) (usingStatisticsType | defaultCostClause (COMMA_ defaultSelectivityClause)? | defaultSelectivityClause (COMMA_ defaultCostClause)?) ; storageTableClause : WITH (SYSTEM | USER) MANAGED STORAGE TABLES ; usingStatisticsType : USING (statisticsTypeName | NULL) ; defaultCostClause : DEFAULT COST LP_ cpuCost COMMA_ ioCost COMMA_ networkCost RP_ ; defaultSelectivityClause : DEFAULT SELECTIVITY defaultSelectivity ; disassociateStatistics : DISASSOCIATE STATISTICS FROM (COLUMNS tableName DOT_ columnName (COMMA_ tableName DOT_ columnName)* | FUNCTIONS function (COMMA_ function)* | PACKAGES packageName (COMMA_ packageName)* | TYPES typeName (COMMA_ typeName)* | INDEXES indexName (COMMA_ indexName)* | INDEXTYPES indextypeName (COMMA_ indextypeName)*) FORCE? ; audit : AUDIT (auditPolicyClause | contextClause) ; noAudit : NOAUDIT (noAuditPolicyClause | contextClause) ; auditPolicyClause : POLICY policyName (byUsersWithRoles | (BY | EXCEPT) username (COMMA_ username)*)? (WHENEVER NOT? SUCCESSFUL)? ; noAuditPolicyClause : POLICY policyName (byUsersWithRoles | BY username (COMMA_ username)*)? (WHENEVER NOT? SUCCESSFUL)? ; byUsersWithRoles : BY USERS WITH GRANTED ROLES roleName (COMMA_ roleName)* ; contextClause : contextNamespaceAttributesClause (COMMA_ contextNamespaceAttributesClause)* (BY username (COMMA_ username)*)? ; contextNamespaceAttributesClause : CONTEXT NAMESPACE namespace ATTRIBUTES attributeName (COMMA_ attributeName)* ; comment : COMMENT ON ( | AUDIT POLICY policyName | COLUMN (tableName | viewName | materializedViewName) DOT_ columnName | EDITION editionName | INDEXTYPE indextypeName | MATERIALIZED VIEW materializedViewName | MINING MODEL modelName | OPERATOR operatorName | TABLE (tableName | viewName) ) IS STRING_ ; flashbackDatabase : FLASHBACK STANDBY? PLUGGABLE? DATABASE databaseName? ( TO (scnTimestampClause | restorePointClause) | TO BEFORE (scnTimestampClause | RESETLOGS)) ; scnTimestampClause : (SCN | TIMESTAMP) scnTimestampExpr ; restorePointClause : RESTORE POINT restorePoint ; flashbackTable : FLASHBACK TABLE tableName TO ( (scnTimestampClause | restorePointClause) ((ENABLE | DISABLE) TRIGGERS)? | BEFORE DROP renameToTable? ) ; renameToTable : RENAME TO tableName ; purge : PURGE (TABLE tableName | INDEX indexName | TABLESPACE tablespaceName (USER username)? | TABLESPACE SET tablespaceSetName (USER username)? | RECYCLEBIN | DBA_RECYCLEBIN) ; rename : RENAME name TO name ; createDatabase : CREATE DATABASE databaseName? createDatabaseClauses+ ; createDatabaseClauses : USER SYS IDENTIFIED BY password | USER SYSTEM IDENTIFIED BY password | CONTROLFILE REUSE | MAXDATAFILES INTEGER_ | MAXINSTANCES INTEGER_ | CHARACTER SET databaseCharset | NATIONAL CHARACTER SET nationalCharset | SET DEFAULT bigOrSmallFiles TABLESPACE | databaseLoggingClauses | tablespaceClauses | setTimeZoneClause | bigOrSmallFiles? USER_DATA TABLESPACE tablespaceName DATAFILE datafileTempfileSpec (COMMA_ datafileTempfileSpec)* | enablePluggableDatabase | databaseName USING MIRROR COPY mirrorName ; databaseLoggingClauses : LOGFILE (GROUP INTEGER_)? fileSpecification (COMMA_ (GROUP INTEGER_)? fileSpecification)* | MAXLOGFILES INTEGER_ | MAXLOGMEMBERS INTEGER_ | MAXLOGHISTORY INTEGER_ | (ARCHIVELOG | NOARCHIVELOG) | FORCE LOGGING | SET STANDBY NOLOGGING FOR (DATA AVAILABILITY | LOAD PERFORMANCE) ; tablespaceClauses : EXTENT MANAGEMENT LOCAL | DATAFILE fileSpecifications | SYSAUX DATAFILE fileSpecifications | defaultTablespace | defaultTempTablespace | undoTablespace ; defaultTablespace : DEFAULT TABLESPACE tablespaceName (DATAFILE datafileTempfileSpec)? extentManagementClause? ; defaultTempTablespace : bigOrSmallFiles? DEFAULT (TEMPORARY TABLESPACE | LOCAL TEMPORARY TABLESPACE FOR (ALL | LEAF)) tablespaceName (TEMPFILE fileSpecifications)? extentManagementClause? ; undoTablespace : bigOrSmallFiles? UNDO TABLESPACE tablespaceName (DATAFILE fileSpecifications)? ; bigOrSmallFiles : BIGFILE | SMALLFILE ; extentManagementClause : EXTENT MANAGEMENT LOCAL (AUTOALLOCATE | UNIFORM (SIZE sizeClause)?)? ; enablePluggableDatabase : ENABLE PLUGGABLE DATABASE (SEED fileNameConvert? (SYSTEM tablespaceDatafileClauses)? (SYSAUX tablespaceDatafileClauses)?)? undoModeClause? ; fileNameConvert : FILE_NAME_CONVERT EQ_ (LP_ replaceFileNamePattern (COMMA_ replaceFileNamePattern)* RP_| NONE) ; replaceFileNamePattern : filenamePattern COMMA_ filenamePattern ; tablespaceDatafileClauses : DATAFILES (SIZE sizeClause | autoextendClause)+ ; createDatabaseLink : CREATE SHARED? PUBLIC? DATABASE LINK dbLink (connectToClause | dbLinkAuthentication)* (USING connectString)? ; alterDatabaseLink : ALTER SHARED? PUBLIC? DATABASE LINK dbLink ( | CONNECT TO username IDENTIFIED BY password dbLinkAuthentication? | dbLinkAuthentication ) ; dropDatabaseLink : DROP PUBLIC? DATABASE LINK dbLink ; connectToClause : CONNECT TO (CURRENT_USER | username IDENTIFIED BY password dbLinkAuthentication?) ; dbLinkAuthentication : AUTHENTICATED BY username IDENTIFIED BY password ; createDimension : CREATE DIMENSION dimensionName levelClause+ (hierarchyClause | attributeClause+ | extendedAttrbuteClause)+ ; levelClause : LEVEL level IS (columnName | LP_ columnName (COMMA_ columnName)* RP_) (SKIP_SYMBOL WHEN NULL)? ; hierarchyClause : HIERARCHY hierarchyName LP_ level (CHILD OF level)+ dimensionJoinClause* RP_ ; dimensionJoinClause : JOIN KEY (columnName | LP_ columnName (COMMA_ columnName)* RP_) REFERENCES level ; attributeClause : ATTRIBUTE level DETERMINES (columnName | LP_ columnName (COMMA_ columnName)* RP_) ; extendedAttrbuteClause : ATTRIBUTE attributeName (LEVEL level DETERMINES (columnName | LP_ columnName (COMMA_ columnName)* RP_))+ ; alterDimension : ALTER DIMENSION dimensionName (alterDimensionAddClause* | alterDimensionDropClause* | COMPILE) ; alterDimensionAddClause : ADD (levelClause | hierarchyClause | attributeClause | extendedAttrbuteClause) ; alterDimensionDropClause : DROP (LEVEL level (RESTRICT | CASCADE)? | HIERARCHY hierarchyName | ATTRIBUTE attributeName (LEVEL level (COLUMN columnName (COMMA_ COLUMN columnName)*)?)?) ; dropDimension : DROP DIMENSION dimensionName ; dropDirectory : DROP DIRECTORY directoryName ; createFunction : CREATE (OR REPLACE)? (EDITIONABLE | NONEDITIONABLE)? FUNCTION plsqlFunctionSource ; plsqlFunctionSource : function (LP_ parameterDeclaration (COMMA_ parameterDeclaration)* RP_)? RETURN dataType sharingClause? (invokerRightsClause | accessibleByClause | defaultCollationoOptionClause | deterministicClause | parallelEnableClause | resultCacheClause | aggregateClause | pipelinedClause | sqlMacroClause)* (IS | AS) callSpec ; parameterDeclaration : parameterName (IN? dataType ((COLON_ EQ_ | DEFAULT) expr)? | IN? OUT NOCOPY? dataType)? ; sharingClause : SHARING EQ_ (METADATA | NONE) ; invokerRightsClause : AUTHID (CURRENT_USER DEFINER) ; accessibleByClause : ACCESSIBLE BY LP_ accessor (COMMA_ accessor)* RP_ ; accessor : unitKind unitName ; unitKind : FUNCTION | PROCEDURE | PACKAGE | TRIGGER | TYPE ; defaultCollationoOptionClause : DEFAULT COLLATION collationOption ; collationOption : USING_NLS_COMP ; deterministicClause : DETERMINISTIC ; parallelEnableClause : PARALLEL_ENABLE (LP_ PARTITION argument BY (ANY | (HASH | RANGE) LP_ columnName (COMMA_ columnName)* RP_ streamingCluase? | VALUE LP_ columnName RP_) RP_)? ; streamingCluase : (ORDER | CLUSTER) expr BY LP_ columnName (COMMA_ columnName)* RP_ ; resultCacheClause : RESULT_CACHE (RELIES_ON LP_ (dataSource (COMMA_ dataSource)*)? RP_)? ; aggregateClause : AGGREGATE USING implementationType ; pipelinedClause : PIPELINED ((USING implementationType)? | (ROW | TABLE) POLYMORPHIC (USING implementationPackage)?) ; sqlMacroClause : SQL_MARCO ; callSpec : javaDeclaration | cDeclaration ; javaDeclaration : LANGUAGE JAVA NAME STRING_ ; cDeclaration : (LANGUAGE SINGLE_C | EXTERNAL) ((NAME name)? LIBRARY libName| LIBRARY libName (NAME name)?) (AGENT IN RP_ argument (COMMA_ argument)* LP_)? (WITH CONTEXT)? (PARAMETERS LP_ externalParameter (COMMA_ externalParameter)* RP_)? ; externalParameter : (CONTEXT | SELF (TDO | property)? | (parameterName | RETURN) property? (BY REFERENCE)? externalDatatype) ; property : (INDICATOR (STRUCT | TDO)? | LENGTH | DURATION | MAXLEN | CHARSETID | CHARSETFORM) ; alterAnalyticView : ALTER ANALYTIC VIEW analyticViewName (RENAME TO analyticViewName | COMPILE) ; alterAttributeDimension : ALTER ATTRIBUTE DIMENSION (schemaName DOT_)? attributeDimensionName (RENAME TO attributeDimensionName | COMPILE) ; createSequence : CREATE SEQUENCE (schemaName DOT_)? sequenceName (SHARING EQ_ (METADATA | DATA | NONE))? createSequenceClause+ ; createSequenceClause : (INCREMENT BY | START WITH) INTEGER_ | MAXVALUE INTEGER_ | NOMAXVALUE | MINVALUE INTEGER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE INTEGER_ | NOCACHE | ORDER | NOORDER | KEEP | NOKEEP | SCALE (EXTEND | NOEXTEND) | NOSCALE | SHARD (EXTEND | NOEXTEND) | NOSHARD | SESSION | GLOBAL ; alterSequence : ALTER SEQUENCE (schemaName DOT_)? sequenceName alterSequenceClause+ ; alterSequenceClause : (INCREMENT BY | START WITH) INTEGER_ | MAXVALUE INTEGER_ | NOMAXVALUE | MINVALUE INTEGER_ | NOMINVALUE | RESTART | CYCLE | NOCYCLE | CACHE INTEGER_ | NOCACHE | ORDER | NOORDER | KEEP | NOKEEP | SCALE (EXTEND | NOEXTEND) | NOSCALE | SHARD (EXTEND | NOEXTEND) | NOSHARD | SESSION | GLOBAL ; createContext : CREATE (OR REPLACE)? CONTEXT namespace USING (schemaName DOT_)? packageName sharingClause? (initializedClause | accessedClause)? ; initializedClause : INITIALIZED (EXTERNALLY | GLOBALLY) ; accessedClause : ACCESSED GLOBALLY ; createSPFile : CREATE SPFILE (EQ_ spfileName)? FROM (PFILE (EQ_ pfileName)? (AS COPY)? | MEMORY) ; createPFile : CREATE PFILE (EQ_ pfileName)? FROM (SPFILE (EQ_ spfileName)? (AS COPY)? | MEMORY) ; createControlFile : CREATE CONTROLFILE REUSE? SET? DATABASE databaseName logfileForControlClause? resetLogsOrNot ( MAXLOGFILES INTEGER_ | MAXLOGMEMBERS INTEGER_ | MAXLOGHISTORY INTEGER_ | MAXDATAFILES INTEGER_ | MAXINSTANCES INTEGER_ | ARCHIVELOG | NOARCHIVELOG | FORCE LOGGING | SET STANDBY NOLOGGING FOR (DATA AVAILABILITY | LOAD PERFORMANCE) )* characterSetClause? ; resetLogsOrNot : ( RESETLOGS | NORESETLOGS) (DATAFILE fileSpecifications)? ; logfileForControlClause : LOGFILE (GROUP INTEGER_)? fileSpecification (COMMA_ (GROUP INTEGER_)? fileSpecification)+ ; characterSetClause : CHARACTER SET characterSetName ; createFlashbackArchive : CREATE FLASHBACK ARCHIVE DEFAULT? flashbackArchiveName tablespaceClause flashbackArchiveQuota? (NO? OPTIMIZE DATA)? flashbackArchiveRetention ; flashbackArchiveQuota : QUOTA INTEGER_ quotaUnit ; flashbackArchiveRetention : RETENTION INTEGER_ (YEAR | MONTH | DAY) ; alterFlashbackArchive : ALTER FLASHBACK ARCHIVE flashbackArchiveName ( SET DEFAULT | (ADD | MODIFY) TABLESPACE tablespaceName flashbackArchiveQuota? | REMOVE TABLESPACE tablespaceName | MODIFY RETENTION flashbackArchiveRetention | PURGE purgeClause | NO? OPTIMIZE DATA) ; purgeClause : ALL | BEFORE (SCN expr | TIMESTAMP expr) ; dropFlashbackArchive : DROP FLASHBACK ARCHIVE flashbackArchiveName ; createDiskgroup : CREATE DISKGROUP diskgroupName (redundancyClause REDUNDANCY)? diskClause+ attribute? ; redundancyClause : HIGH | NORMAL | FLEX | EXTENDED (SITE siteName)? | EXTERNAL ; diskClause : (QUORUM | REGULAR)? (FAILGROUP diskgroupName)? DISK qualifieDiskClause (COMMA_ qualifieDiskClause)* ; qualifieDiskClause : searchString (NAME diskName)? (SIZE sizeClause)? (FORCE | NOFORCE)? ; attribute : ATTRIBUTE attributeNameAndValue (COMMA_ attributeNameAndValue)* ; attributeNameAndValue : SQ_ attributeName SQ_ EQ_ SQ_ attributeValue SQ_ ; dropDiskgroup : DROP DISKGROUP diskgroupName contentsClause? ; contentsClause : ((FORCE? INCLUDING) | EXCLUDING) CONTENTS ; createRollbackSegment : CREATE PUBLIC? ROLLBACK SEGMENT rollbackSegment ((TABLESPACE tablespaceName) | storageClause)* ; dropRollbackSegment : DROP ROLLBACK SEGMENT rollbackSegment ; createLockdownProfile : CREATE LOCKDOWN PROFILE profileName (staticBaseProfile | dynamicBaseProfile)? ; staticBaseProfile : FROM profileName ; dynamicBaseProfile : INCLUDING profileName ; dropLockdownProfile : DROP LOCKDOWN PROFILE profileName ; createInmemoryJoinGroup : CREATE INMEMORY JOIN GROUP (schemaName DOT_)? joinGroupName LP_ tableColumnClause COMMA_ tableColumnClause (COMMA_ tableColumnClause)* RP_ ; tableColumnClause : (schemaName DOT_)? tableName LP_ columnName RP_ ; ",16310,True,3230.640352816496,median "/* Feathers Copyright 2012-2014 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls.text { import feathers.core.FeathersControl; import feathers.core.ITextRenderer; import feathers.skins.IStyleProvider; import flash.display.BitmapData; import flash.display.DisplayObjectContainer; import flash.display.Sprite; import flash.display3D.Context3DProfile; import flash.filters.BitmapFilter; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.engine.ContentElement; import flash.text.engine.ElementFormat; import flash.text.engine.FontDescription; import flash.text.engine.SpaceJustifier; import flash.text.engine.TabStop; import flash.text.engine.TextBaseline; import flash.text.engine.TextBlock; import flash.text.engine.TextElement; import flash.text.engine.TextJustifier; import flash.text.engine.TextLine; import flash.text.engine.TextLineValidity; import flash.text.engine.TextRotation; import starling.core.RenderSupport; import starling.core.Starling; import starling.display.Image; import starling.textures.ConcreteTexture; import starling.textures.Texture; import starling.utils.getNextPowerOfTwo; /** * Renders text with a native flash.text.engine.TextBlock from * Flash Text Engine (FTE), and draws it to BitmapData to * convert to Starling textures. Textures are completely managed by this * component, and they will be automatically disposed when the component is * disposed. * *

For longer passages of text, this component will stitch together * multiple individual textures both horizontally and vertically, as a grid, * if required. This may require quite a lot of texture memory, possibly * exceeding the limits of some mobile devices, so use this component with * caution when displaying a lot of text.

* * @see http://wiki.starling-framework.org/feathers/text-renderers * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html flash.text.engine.TextBlock */ public class TextBlockTextRenderer extends FeathersControl implements ITextRenderer { /** * @private */ private static const HELPER_POINT:Point = new Point(); /** * @private */ private static const HELPER_MATRIX:Matrix = new Matrix(); /** * @private */ private static const HELPER_RECTANGLE:Rectangle = new Rectangle(); /** * @private */ private static var HELPER_TEXT_LINES:Vector. = new []; /** * @private * This is enforced by the runtime. */ protected static const MAX_TEXT_LINE_WIDTH:Number = 1000000; /** * @private */ protected static const LINE_FEED:String = ""\\n""; /** * @private */ protected static const CARRIAGE_RETURN:String = ""\\r""; /** * @private */ protected static const FUZZY_TRUNCATION_DIFFERENCE:Number = 0.000001; /** * The text will be positioned to the left edge. * * @see #textAlign */ public static const TEXT_ALIGN_LEFT:String = ""left""; /** * The text will be centered horizontally. * * @see #textAlign */ public static const TEXT_ALIGN_CENTER:String = ""center""; /** * The text will be positioned to the right edge. * * @see #textAlign */ public static const TEXT_ALIGN_RIGHT:String = ""right""; /** * The default IStyleProvider for all TextBlockTextRenderer * components. * * @default null * @see feathers.core.FeathersControl#styleProvider */ public static var globalStyleProvider:IStyleProvider; /** * Constructor. */ public function TextBlockTextRenderer() { super(); this.isQuickHitAreaEnabled = true; } /** * The TextBlock instance used to render the text before taking a * texture snapshot. */ protected var textBlock:TextBlock; /** * An image that displays a snapshot of the native TextBlock * in the Starling display list when the editor doesn't have focus. */ protected var textSnapshot:Image; /** * If multiple snapshots are needed due to texture size limits, the * snapshots appearing after the first are stored here. */ protected var textSnapshots:Vector.; /** * @private */ protected var _textSnapshotScrollX:Number = 0; /** * @private */ protected var _textSnapshotScrollY:Number = 0; /** * @private */ protected var _textSnapshotOffsetX:Number = 0; /** * @private */ protected var _textSnapshotOffsetY:Number = 0; /** * @private */ protected var _textLineContainer:Sprite; /** * @private */ protected var _textLines:Vector. = new []; /** * @private */ protected var _measurementTextLineContainer:Sprite; /** * @private */ protected var _measurementTextLines:Vector. = new []; /** * @private */ protected var _previousContentWidth:Number = NaN; /** * @private */ protected var _previousContentHeight:Number = NaN; /** * @private */ protected var _snapshotWidth:int = 0; /** * @private */ protected var _snapshotHeight:int = 0; /** * @private */ protected var _needsNewTexture:Boolean = false; /** * @private */ protected var _truncationOffset:int = 0; /** * @private */ protected var _textElement:TextElement; /** * @private */ override protected function get defaultStyleProvider():IStyleProvider { return TextBlockTextRenderer.globalStyleProvider; } /** * @private */ protected var _text:String; /** * @inheritDoc * *

In the following example, the text is changed:

* * * textRenderer.text = ""Lorem ipsum""; * * @default """" */ public function get text():String { return this._textElement ? this._text : null; } /** * @private */ public function set text(value:String):void { if(this._text == value) { return; } this._text = value; if(!this._textElement) { this._textElement = new TextElement(value); } this._textElement.text = value; this.content = this._textElement; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _content:ContentElement; /** * Sets the contents of the TextBlock to a complex value * that is more than simple text. If the text property is * set after the content property, the content * property will be replaced with a TextElement. * *

In the following example, the content is changed to a * GroupElement:

* * * textRenderer.content = new GroupElement( element ); * *

To simply display a string value, use the text property * instead:

* * * textRenderer.text = ""Lorem Ipsum""; * * @default null * * @see #text */ public function get content():ContentElement { return this._content; } /** * @private */ public function set content(value:ContentElement):void { if(this._content == value) { return; } if(value is TextElement) { this._textElement = TextElement(value); } else { this._textElement = null; } this._content = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _elementFormat:ElementFormat; /** * The font and styles used to draw the text. This property will be * ignored if the content is not a TextElement instance. * *

In the following example, the element format is changed:

* * * textRenderer.elementFormat = new ElementFormat( new FontDescription( ""Source Sans Pro"" ) ); * * @default null * * @see #disabledElementFormat * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/ElementFormat.html flash.text.engine.ElementFormat */ public function get elementFormat():ElementFormat { return this._elementFormat; } /** * @private */ public function set elementFormat(value:ElementFormat):void { if(this._elementFormat == value) { return; } this._elementFormat = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _disabledElementFormat:ElementFormat; /** * The font and styles used to draw the text when the component is * disabled. This property will be ignored if the content is not a * TextElement instance. * *

In the following example, the disabled element format is changed:

* * * textRenderer.isEnabled = false; * textRenderer.disabledElementFormat = new ElementFormat( new FontDescription( ""Source Sans Pro"" ) ); * * @default null * * @see #elementFormat * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/ElementFormat.html flash.text.engine.ElementFormat */ public function get disabledElementFormat():ElementFormat { return this._disabledElementFormat; } /** * @private */ public function set disabledElementFormat(value:ElementFormat):void { if(this._disabledElementFormat == value) { return; } this._disabledElementFormat = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _leading:Number = 0; /** * The amount of vertical space, in pixels, between lines. * *

In the following example, the leading is changed to 20 pixels:

* * * textRenderer.leading = 20; * * @default 0 */ public function get leading():Number { return this._leading; } /** * @private */ public function set leading(value:Number):void { if(this._leading == value) { return; } this._leading = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _textAlign:String = TEXT_ALIGN_LEFT; /** * The alignment of the text. For justified text, see the * textJustifier property. * *

In the following example, the leading is changed to 20 pixels:

* * * textRenderer.textAlign = TextBlockTextRenderer.TEXT_ALIGN_CENTER; * * @default TextBlockTextRenderer.TEXT_ALIGN_LEFT * * @see #TEXT_ALIGN_LEFT * @see #TEXT_ALIGN_CENTER * @see #TEXT_ALIGN_RIGHT * @see #textJustifier */ public function get textAlign():String { return this._textAlign; } /** * @private */ public function set textAlign(value:String):void { if(this._textAlign == value) { return; } this._textAlign = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _wordWrap:Boolean = false; /** * Determines if the text wraps to the next line when it reaches the * width of the component. * *

In the following example, word wrap is enabled:

* * * textRenderer.wordWrap = true; * * @default false */ public function get wordWrap():Boolean { return this._wordWrap; } /** * @private */ public function set wordWrap(value:Boolean):void { if(this._wordWrap == value) { return; } this._wordWrap = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @inheritDoc */ public function get baseline():Number { if(this._textLines.length == 0) { return 0; } return this._textLines[0].ascent; } /** * @private */ protected var _applyNonLinearFontScaling:Boolean = true; /** * Specifies that you want to enhance screen appearance at the expense * of what-you-see-is-what-you-get (WYSIWYG) print fidelity. * *

In the following example, this property is changed to false:

* * * textRenderer.applyNonLinearFontScaling = false; * * @default true * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html#applyNonLinearFontScaling Full description of flash.text.engine.TextBlock.applyNonLinearFontScaling in Adobe's Flash Platform API Reference */ public function get applyNonLinearFontScaling():Boolean { return this._applyNonLinearFontScaling; } /** * @private */ public function set applyNonLinearFontScaling(value:Boolean):void { if(this._applyNonLinearFontScaling == value) { return; } this._applyNonLinearFontScaling = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _baselineFontDescription:FontDescription; /** * The font used to determine the baselines for all the lines created from the block, independent of their content. * *

In the following example, the baseline font description is changed:

* * * textRenderer.baselineFontDescription = new FontDescription( ""Source Sans Pro"", FontWeight.BOLD ); * * @default null * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html#baselineFontDescription Full description of flash.text.engine.TextBlock.baselineFontDescription in Adobe's Flash Platform API Reference * @see #baselineFontSize */ public function get baselineFontDescription():FontDescription { return this._baselineFontDescription; } /** * @private */ public function set baselineFontDescription(value:FontDescription):void { if(this._baselineFontDescription == value) { return; } this._baselineFontDescription = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _baselineFontSize:Number = 12; /** * The font size used to calculate the baselines for the lines created * from the block. * *

In the following example, the baseline font size is changed:

* * * textRenderer.baselineFontSize = 20; * * @default 12 * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html#baselineFontSize Full description of flash.text.engine.TextBlock.baselineFontSize in Adobe's Flash Platform API Reference * @see #baselineFontDescription */ public function get baselineFontSize():Number { return this._baselineFontSize; } /** * @private */ public function set baselineFontSize(value:Number):void { if(this._baselineFontSize == value) { return; } this._baselineFontSize = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _baselineZero:String = TextBaseline.ROMAN; /** * Specifies which baseline is at y=0 for lines created from this block. * *

In the following example, the baseline zero is changed:

* * * textRenderer.baselineZero = TextBaseline.ASCENT; * * @default TextBaseline.ROMAN * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html#baselineZero Full description of flash.text.engine.TextBlock.baselineZero in Adobe's Flash Platform API Reference * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBaseline.html flash.text.engine.TextBaseline */ public function get baselineZero():String { return this._baselineZero; } /** * @private */ public function set baselineZero(value:String):void { if(this._baselineZero == value) { return; } this._baselineZero = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _bidiLevel:int = 0; /** * Specifies the bidirectional paragraph embedding level of the text * block. * *

In the following example, the bidi level is changed:

* * * textRenderer.bidiLevel = 1; * * @default 0 * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html#bidiLevel Full description of flash.text.engine.TextBlock.bidiLevel in Adobe's Flash Platform API Reference */ public function get bidiLevel():int { return this._bidiLevel; } /** * @private */ public function set bidiLevel(value:int):void { if(this._bidiLevel == value) { return; } this._bidiLevel = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _lineRotation:String = TextRotation.ROTATE_0; /** * Rotates the text lines in the text block as a unit. * *

In the following example, the line rotation is changed:

* * * textRenderer.lineRotation = TextRotation.ROTATE_90; * * @default TextRotation.ROTATE_0 * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html#lineRotation Full description of flash.text.engine.TextBlock.lineRotation in Adobe's Flash Platform API Reference * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextRotation.html flash.text.engine.TextRotation */ public function get lineRotation():String { return this._lineRotation; } /** * @private */ public function set lineRotation(value:String):void { if(this._lineRotation == value) { return; } this._lineRotation = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _tabStops:Vector.; /** * Specifies the tab stops for the text in the text block, in the form * of a Vector of TabStop objects. * *

In the following example, the tab stops changed:

* * * textRenderer.tabStops = new <TabStop>[ new TabStop( TabAlignment.CENTER ) ]; * * @default null * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html#tabStops Full description of flash.text.engine.TextBlock.tabStops in Adobe's Flash Platform API Reference */ public function get tabStops():Vector. { return this._tabStops; } /** * @private */ public function set tabStops(value:Vector.):void { if(this._tabStops == value) { return; } this._tabStops = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _textJustifier:TextJustifier = new SpaceJustifier(); /** * Specifies the TextJustifier to use during line creation. * *

In the following example, the text justifier is changed:

* * * textRenderer.textJustifier = new SpaceJustifier( ""en"", LineJustification.ALL_BUT_LAST ); * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html#textJustifier Full description of flash.text.engine.TextBlock.textJustifier in Adobe's Flash Platform API Reference */ public function get textJustifier():TextJustifier { return this._textJustifier; } /** * @private */ public function set textJustifier(value:TextJustifier):void { if(this._textJustifier == value) { return; } this._textJustifier = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _userData:*; /** * Provides a way for the application to associate arbitrary data with * the text block. * *

In the following example, the user data is changed:

* * * textRenderer.userData = { author: ""William Shakespeare"", title: ""Much Ado About Nothing"" }; * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html#userData Full description of flash.text.engine.TextBlock.userData in Adobe's Flash Platform API Reference */ public function get userData():* { return this._userData; } /** * @private */ public function set userData(value:*):void { if(this._userData === value) { return; } this._userData = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _snapToPixels:Boolean = true; /** * Determines if the text should be snapped to the nearest whole pixel * when rendered. When this is false, text may be displayed * on sub-pixels, which often results in blurred rendering due to * texture smoothing. * *

In the following example, the text is not snapped to pixels:

* * * textRenderer.snapToPixels = false; * * @default true */ public function get snapToPixels():Boolean { return this._snapToPixels; } /** * @private */ public function set snapToPixels(value:Boolean):void { this._snapToPixels = value; } /** * @private */ protected var _maxTextureDimensions:int = 2048; /** * The maximum size of individual textures that are managed by this text * renderer. Must be a power of 2. A larger value will create fewer * individual textures, but a smaller value may use less overall texture * memory by incrementing over smaller powers of two. * *

In the following example, the maximum size of the textures is * changed:

* * * renderer.maxTextureDimensions = 4096; * * @default 2048 */ public function get maxTextureDimensions():int { return this._maxTextureDimensions; } /** * @private */ public function set maxTextureDimensions(value:int):void { //check if we can use rectangle textures or not if(Starling.current.profile == Context3DProfile.BASELINE_CONSTRAINED) { value = getNextPowerOfTwo(value); } if(this._maxTextureDimensions == value) { return; } this._maxTextureDimensions = value; this._needsNewTexture = true; this.invalidate(INVALIDATION_FLAG_SIZE); } /** * @private */ protected var _nativeFilters:Array; /** * Native filters to pass to the flash.text.engine.TextLine * instances before creating the texture snapshot. * *

In the following example, the native filters are changed:

* * * renderer.nativeFilters = [ new GlowFilter() ]; * * @default null * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#filters Full description of flash.display.DisplayObject.filters in Adobe's Flash Platform API Reference */ public function get nativeFilters():Array { return this._nativeFilters; } /** * @private */ public function set nativeFilters(value:Array):void { if(this._nativeFilters == value) { return; } this._nativeFilters = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _truncationText:String = ""...""; /** * The text to display at the end of the label if it is truncated. * *

In the following example, the truncation text is changed:

* * * textRenderer.truncationText = "" [more]""; * * @default ""..."" * * @see #truncateToFit */ public function get truncationText():String { return _truncationText; } /** * @private */ public function set truncationText(value:String):void { if(this._truncationText == value) { return; } this._truncationText = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _truncateToFit:Boolean = true; /** * If word wrap is disabled, and the text is longer than the width of * the label, the text may be truncated using truncationText. * *

This feature may be disabled to improve performance.

* *

This feature only works when the text property is * set to a string value. If the content property is set * instead, then the content will not be truncated.

* *

This feature does not currently support the truncation of text * displayed on multiple lines.

* *

In the following example, truncation is disabled:

* * * textRenderer.truncateToFit = false; * * @default true * * @see #truncationText */ public function get truncateToFit():Boolean { return _truncateToFit; } /** * @private */ public function set truncateToFit(value:Boolean):void { if(this._truncateToFit == value) { return; } this._truncateToFit = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ override public function dispose():void { if(this.textSnapshot) { this.textSnapshot.texture.dispose(); this.removeChild(this.textSnapshot, true); this.textSnapshot = null; } if(this.textSnapshots) { var snapshotCount:int = this.textSnapshots.length; for(var i:int = 0; i < snapshotCount; i++) { var snapshot:Image = this.textSnapshots[i]; snapshot.texture.dispose(); this.removeChild(snapshot, true); } this.textSnapshots = null; } //this isn't necessary, but if a memory leak keeps the text renderer //from being garbage collected, freeing up these things may help //ease memory pressure from native filters and other expensive stuff this.textBlock = null; this._textLineContainer = null; this._textLines = null; this._measurementTextLineContainer = null; this._measurementTextLines = null; this._textElement = null; this._content = null; this._previousContentWidth = NaN; this._previousContentHeight = NaN; this._needsNewTexture = false; this._snapshotWidth = 0; this._snapshotHeight = 0; super.dispose(); } /** * @private */ override public function render(support:RenderSupport, parentAlpha:Number):void { if(this.textSnapshot) { if(this._snapToPixels) { this.getTransformationMatrix(this.stage, HELPER_MATRIX); this.textSnapshot.x = this._textSnapshotOffsetX + Math.round(HELPER_MATRIX.tx) - HELPER_MATRIX.tx; this.textSnapshot.y = this._textSnapshotOffsetY + Math.round(HELPER_MATRIX.ty) - HELPER_MATRIX.ty; } else { this.textSnapshot.x = this._textSnapshotOffsetX; this.textSnapshot.y = this._textSnapshotOffsetY; } } super.render(support, parentAlpha); } /** * @inheritDoc */ public function measureText(result:Point = null):Point { if(!result) { result = new Point(); } var needsWidth:Boolean = this.explicitWidth !== this.explicitWidth; //isNaN var needsHeight:Boolean = this.explicitHeight !== this.explicitHeight; //isNaN if(!needsWidth && !needsHeight) { result.x = this.explicitWidth; result.y = this.explicitHeight; return result; } //if a parent component validates before we're added to the stage, //measureText() may be called before initialization, so we need to //force it. if(!this._isInitialized) { this.initializeInternal(); } this.commit(); result = this.measure(result); return result; } /** * @private */ override protected function initialize():void { if(!this.textBlock) { this.textBlock = new TextBlock(); } if(!this._textLineContainer) { this._textLineContainer = new Sprite(); } if(!this._measurementTextLineContainer) { this._measurementTextLineContainer = new Sprite(); } } /** * @private */ override protected function draw():void { var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); this.commit(); sizeInvalid = this.autoSizeIfNeeded() || sizeInvalid; this.layout(sizeInvalid); } /** * @private */ protected function commit():void { var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); if(dataInvalid || stylesInvalid || stateInvalid) { if(this._textElement) { if(!this._isEnabled && this._disabledElementFormat) { this._textElement.elementFormat = this._disabledElementFormat; } else { if(!this._elementFormat) { this._elementFormat = new ElementFormat(); } this._textElement.elementFormat = this._elementFormat; } } } if(stylesInvalid) { this.textBlock.applyNonLinearFontScaling = this._applyNonLinearFontScaling; this.textBlock.baselineFontDescription = this._baselineFontDescription; this.textBlock.baselineFontSize = this._baselineFontSize; this.textBlock.baselineZero = this._baselineZero; this.textBlock.bidiLevel = this._bidiLevel; this.textBlock.lineRotation = this._lineRotation; this.textBlock.tabStops = this._tabStops; this.textBlock.textJustifier = this._textJustifier; this.textBlock.userData = this._userData; } if(dataInvalid) { this.textBlock.content = this._content; } } /** * @private */ protected function measure(result:Point = null):Point { if(!result) { result = new Point(); } var needsWidth:Boolean = this.explicitWidth !== this.explicitWidth; //isNaN var needsHeight:Boolean = this.explicitHeight !== this.explicitHeight; //isNaN var newWidth:Number = this.explicitWidth; var newHeight:Number = this.explicitHeight; if(needsWidth) { newWidth = this._maxWidth; if(newWidth > MAX_TEXT_LINE_WIDTH) { newWidth = MAX_TEXT_LINE_WIDTH; } } if(needsHeight) { newHeight = this._maxHeight; } this.refreshTextLines(this._measurementTextLines, this._measurementTextLineContainer, newWidth, newHeight); if(needsWidth) { newWidth = this._measurementTextLineContainer.width; if(newWidth > this._maxWidth) { newWidth = this._maxWidth; } } if(needsHeight) { newHeight = this._measurementTextLineContainer.height; if(newHeight <= 0 && this._elementFormat) { newHeight = this._elementFormat.fontSize; } } result.x = newWidth; result.y = newHeight; return result; } /** * @private */ protected function layout(sizeInvalid:Boolean):void { var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); if(sizeInvalid) { var canUseRectangleTexture:Boolean = Starling.current.profile != Context3DProfile.BASELINE_CONSTRAINED; var rectangleSnapshotWidth:Number = this.actualWidth * Starling.contentScaleFactor; if(canUseRectangleTexture) { if(rectangleSnapshotWidth > this._maxTextureDimensions) { this._snapshotWidth = int(rectangleSnapshotWidth / this._maxTextureDimensions) * this._maxTextureDimensions + (rectangleSnapshotWidth % this._maxTextureDimensions); } else { this._snapshotWidth = rectangleSnapshotWidth; } } else { if(rectangleSnapshotWidth > this._maxTextureDimensions) { this._snapshotWidth = int(rectangleSnapshotWidth / this._maxTextureDimensions) * this._maxTextureDimensions + getNextPowerOfTwo(rectangleSnapshotWidth % this._maxTextureDimensions); } else { this._snapshotWidth = getNextPowerOfTwo(rectangleSnapshotWidth); } } var rectangleSnapshotHeight:Number = this.actualHeight * Starling.contentScaleFactor; if(canUseRectangleTexture) { if(rectangleSnapshotHeight > this._maxTextureDimensions) { this._snapshotHeight = int(rectangleSnapshotHeight / this._maxTextureDimensions) * this._maxTextureDimensions + (rectangleSnapshotHeight % this._maxTextureDimensions); } else { this._snapshotHeight = rectangleSnapshotHeight; } } else { if(rectangleSnapshotHeight > this._maxTextureDimensions) { this._snapshotHeight = int(rectangleSnapshotHeight / this._maxTextureDimensions) * this._maxTextureDimensions + getNextPowerOfTwo(rectangleSnapshotHeight % this._maxTextureDimensions); } else { this._snapshotHeight = getNextPowerOfTwo(rectangleSnapshotHeight); } } var textureRoot:ConcreteTexture = this.textSnapshot ? this.textSnapshot.texture.root : null; this._needsNewTexture = this._needsNewTexture || !this.textSnapshot || this._snapshotWidth != textureRoot.width || this._snapshotHeight != textureRoot.height; } //instead of checking sizeInvalid, which will often be triggered by //changing maxWidth or something for measurement, we check against //the previous actualWidth/Height used for the snapshot. if(stylesInvalid || dataInvalid || stateInvalid || this._needsNewTexture || this.actualWidth != this._previousContentWidth || this.actualHeight != this._previousContentHeight) { this._previousContentWidth = this.actualWidth; this._previousContentHeight = this.actualHeight; if(this._content) { this.refreshTextLines(this._textLines, this._textLineContainer, this.actualWidth, this.actualHeight); this.refreshSnapshot(); } if(this.textSnapshot) { this.textSnapshot.visible = this._content !== null; } } } /** * If the component's dimensions have not been set explicitly, it will * measure its content and determine an ideal size for itself. If the * explicitWidth or explicitHeight member * variables are set, those value will be used without additional * measurement. If one is set, but not the other, the dimension with the * explicit value will not be measured, but the other non-explicit * dimension will still need measurement. * *

Calls setSizeInternal() to set up the * actualWidth and actualHeight member * variables used for layout.

* *

Meant for internal use, and subclasses may override this function * with a custom implementation.

*/ protected function autoSizeIfNeeded():Boolean { var needsWidth:Boolean = this.explicitWidth !== this.explicitWidth; //isNaN var needsHeight:Boolean = this.explicitHeight !== this.explicitHeight; //isNaN if(!needsWidth && !needsHeight) { return false; } this.measure(HELPER_POINT); return this.setSizeInternal(HELPER_POINT.x, HELPER_POINT.y, false); } /** * @private */ protected function measureNativeFilters(bitmapData:BitmapData, result:Rectangle = null):Rectangle { if(!result) { result = new Rectangle(); } var resultX:Number = 0; var resultY:Number = 0; var resultWidth:Number = 0; var resultHeight:Number = 0; var filterCount:int = this._nativeFilters.length; for(var i:int = 0; i < filterCount; i++) { var filter:BitmapFilter = this._nativeFilters[i]; var filterRect:Rectangle = bitmapData.generateFilterRect(bitmapData.rect, filter); var filterX:Number = filterRect.x; var filterY:Number = filterRect.y; var filterWidth:Number = filterRect.width; var filterHeight:Number = filterRect.height; if(resultX > filterX) { resultX = filterX; } if(resultY > filterY) { resultY = filterY; } if(resultWidth < filterWidth) { resultWidth = filterWidth; } if(resultHeight < filterHeight) { resultHeight = filterHeight; } } result.setTo(resultX, resultY, resultWidth, resultHeight); return result; } /** * @private */ protected function createTextureOnRestoreCallback(snapshot:Image):void { var self:TextBlockTextRenderer = this; var texture:Texture = snapshot.texture; texture.root.onRestore = function():void { var bitmapData:BitmapData = self.drawTextLinesRegionToBitmapData( snapshot.x, snapshot.y, snapshot.width, snapshot.height); texture.root.uploadBitmapData(bitmapData); }; } /** * @private */ protected function drawTextLinesRegionToBitmapData(textLinesX:Number, textLinesY:Number, bitmapWidth:Number, bitmapHeight:Number, bitmapData:BitmapData = null):BitmapData { var scaleFactor:Number = Starling.contentScaleFactor; var clipWidth:Number = (this.actualWidth * scaleFactor) - textLinesX; var clipHeight:Number = (this.actualHeight * scaleFactor) - textLinesY; if(!bitmapData || bitmapData.width != bitmapWidth || bitmapData.height != bitmapHeight) { if(bitmapData) { bitmapData.dispose(); } bitmapData = new BitmapData(bitmapWidth, bitmapHeight, true, 0x00ff00ff); } else { //clear the bitmap data and reuse it bitmapData.fillRect(bitmapData.rect, 0x00ff00ff); } HELPER_MATRIX.tx = -textLinesX - this._textSnapshotScrollX; HELPER_MATRIX.ty = -textLinesY - this._textSnapshotScrollY; HELPER_RECTANGLE.setTo(0, 0, clipWidth, clipHeight); bitmapData.draw(this._textLineContainer, HELPER_MATRIX, null, null, HELPER_RECTANGLE); var useNativeFilters:Boolean = this._nativeFilters && this._nativeFilters.length > 0 && this._snapshotWidth <= this._maxTextureDimensions && this._snapshotHeight <= this._maxTextureDimensions; if(useNativeFilters) { //check to see if the bitmap data must be resized when the //filters are applied. this.measureNativeFilters(bitmapData, HELPER_RECTANGLE); if(bitmapData.rect.equals(HELPER_RECTANGLE)) { //in the ideal situation, we don't even need to resize the //bitmap data. this._textSnapshotOffsetX = 0; this._textSnapshotOffsetY = 0; } else { HELPER_MATRIX.tx -= HELPER_RECTANGLE.x; HELPER_MATRIX.ty -= HELPER_RECTANGLE.y; var newBitmapData:BitmapData = new BitmapData(HELPER_RECTANGLE.width, HELPER_RECTANGLE.height, true, 0x00ff00ff); this._textSnapshotOffsetX = HELPER_RECTANGLE.x; this._textSnapshotOffsetY = HELPER_RECTANGLE.y; HELPER_RECTANGLE.x = 0; HELPER_RECTANGLE.y = 0; newBitmapData.draw(this._textLineContainer, HELPER_MATRIX, null, null, HELPER_RECTANGLE); bitmapData.dispose(); bitmapData = newBitmapData; } } else { this._textSnapshotOffsetX = 0; this._textSnapshotOffsetY = 0; } return bitmapData; } /** * @private */ protected function refreshSnapshot():void { if(this._snapshotWidth == 0 || this._snapshotHeight == 0) { return; } var scaleFactor:Number = Starling.contentScaleFactor; HELPER_MATRIX.identity(); HELPER_MATRIX.scale(scaleFactor, scaleFactor); var totalBitmapWidth:Number = this._snapshotWidth; var totalBitmapHeight:Number = this._snapshotHeight; var xPosition:Number = 0; var yPosition:Number = 0; var bitmapData:BitmapData; var snapshotIndex:int = -1; do { var currentBitmapWidth:Number = totalBitmapWidth; if(currentBitmapWidth > this._maxTextureDimensions) { currentBitmapWidth = this._maxTextureDimensions; } do { var currentBitmapHeight:Number = totalBitmapHeight; if(currentBitmapHeight > this._maxTextureDimensions) { currentBitmapHeight = this._maxTextureDimensions; } bitmapData = this.drawTextLinesRegionToBitmapData(xPosition, yPosition, currentBitmapWidth, currentBitmapHeight, bitmapData); var newTexture:Texture; if(!this.textSnapshot || this._needsNewTexture) { newTexture = Texture.fromBitmapData(bitmapData, false, false, scaleFactor); } var snapshot:Image = null; if(snapshotIndex >= 0) { if(!this.textSnapshots) { this.textSnapshots = new []; } else if(this.textSnapshots.length > snapshotIndex) { snapshot = this.textSnapshots[snapshotIndex] } } else { snapshot = this.textSnapshot; } if(!snapshot) { snapshot = new Image(newTexture); this.addChild(snapshot); } else { if(this._needsNewTexture) { snapshot.texture.dispose(); snapshot.texture = newTexture; snapshot.readjustSize(); } else { //this is faster, if we haven't resized the bitmapdata var existingTexture:Texture = snapshot.texture; existingTexture.root.uploadBitmapData(bitmapData); } } if(newTexture) { this.createTextureOnRestoreCallback(snapshot); } if(snapshotIndex >= 0) { this.textSnapshots[snapshotIndex] = snapshot; } else { this.textSnapshot = snapshot; } snapshot.x = xPosition / scaleFactor; snapshot.y = yPosition / scaleFactor; snapshotIndex++; yPosition += currentBitmapHeight; totalBitmapHeight -= currentBitmapHeight; } while(totalBitmapHeight > 0) xPosition += currentBitmapWidth; totalBitmapWidth -= currentBitmapWidth; yPosition = 0; totalBitmapHeight = this._snapshotHeight; } while(totalBitmapWidth > 0) bitmapData.dispose(); if(this.textSnapshots) { var snapshotCount:int = this.textSnapshots.length; for(var i:int = snapshotIndex; i < snapshotCount; i++) { snapshot = this.textSnapshots[i]; snapshot.texture.dispose(); snapshot.removeFromParent(true); } if(snapshotIndex == 0) { this.textSnapshots = null; } else { this.textSnapshots.length = snapshotIndex; } } this._needsNewTexture = false; } /** * @private */ protected function refreshTextLines(textLines:Vector., textLineParent:DisplayObjectContainer, width:Number, height:Number):void { if(this._textElement) { if(this._text) { this._textElement.text = this._text; if(this._text !== null && this._text.charAt(this._text.length - 1) == "" "") { //add an invisible control character because FTE apparently //doesn't think that it's important to include trailing //spaces in its width measurement. this._textElement.text += String.fromCharCode(3); } } else { //similar to above. this hack ensures that the baseline is //measured properly when the text is an empty string. this._textElement.text = String.fromCharCode(3); } } HELPER_TEXT_LINES.length = 0; var yPosition:Number = 0; var lineCount:int = textLines.length; var lastLine:TextLine; var cacheIndex:int = lineCount; for(var i:int = 0; i < lineCount; i++) { var line:TextLine = textLines[i]; if(line.validity === TextLineValidity.VALID) { line.filters = this._nativeFilters; lastLine = line; textLines[i] = line; continue; } else { line = lastLine; if(lastLine) { yPosition = lastLine.y; //we're using this value in the next loop lastLine = null; } cacheIndex = i; break; } } //copy the invalid text lines over to the helper vector so that we //can reuse them for(; i < lineCount; i++) { HELPER_TEXT_LINES[int(i - cacheIndex)] = textLines[i]; } textLines.length = cacheIndex; if(width >= 0) { var lineStartIndex:int = 0; var canTruncate:Boolean = this._truncateToFit && this._textElement && !this._wordWrap; var pushIndex:int = textLines.length; var inactiveTextLineCount:int = HELPER_TEXT_LINES.length; while(true) { this._truncationOffset = 0; var previousLine:TextLine = line; var lineWidth:Number = width; if(!this._wordWrap) { lineWidth = MAX_TEXT_LINE_WIDTH; } if(inactiveTextLineCount > 0) { var inactiveLine:TextLine = HELPER_TEXT_LINES[0]; line = this.textBlock.recreateTextLine(inactiveLine, previousLine, lineWidth, 0, true); if(line) { HELPER_TEXT_LINES.shift(); inactiveTextLineCount--; } } else { line = this.textBlock.createTextLine(previousLine, lineWidth, 0, true); if(line) { textLineParent.addChild(line); } } if(!line) { //end of text break; } var lineLength:int = line.rawTextLength; var isTruncated:Boolean = false; var difference:Number = 0; while(canTruncate && (difference = line.width - width) > FUZZY_TRUNCATION_DIFFERENCE) { isTruncated = true; if(this._truncationOffset == 0) { //this will quickly skip all of the characters after //the maximum width of the line, instead of going //one by one. var endIndex:int = line.getAtomIndexAtPoint(width, 0); if(endIndex >= 0) { this._truncationOffset = line.rawTextLength - endIndex; } } this._truncationOffset++; var truncatedTextLength:int = lineLength - this._truncationOffset; //we want to start at this line so that the previous //lines don't become invalid. this._textElement.text = this._text.substr(lineStartIndex, truncatedTextLength) + this._truncationText; var lineBreakIndex:int = this._text.indexOf(LINE_FEED, lineStartIndex); if(lineBreakIndex < 0) { lineBreakIndex = this._text.indexOf(CARRIAGE_RETURN, lineStartIndex); } if(lineBreakIndex >= 0) { this._textElement.text += this._text.substr(lineBreakIndex); } line = this.textBlock.recreateTextLine(line, null, lineWidth, 0, true); if(truncatedTextLength <= 0) { break; } } if(pushIndex > 0) { yPosition += this._leading; } yPosition += line.ascent; line.y = yPosition; yPosition += line.descent; line.filters = this._nativeFilters; textLines[pushIndex] = line; pushIndex++; lineStartIndex += lineLength; } } this.alignTextLines(textLines, width, this._textAlign); inactiveTextLineCount = HELPER_TEXT_LINES.length; for(i = 0; i < inactiveTextLineCount; i++) { line = HELPER_TEXT_LINES[i]; textLineParent.removeChild(line); } HELPER_TEXT_LINES.length = 0; } /** * @private */ protected function alignTextLines(textLines:Vector., width:Number, textAlign:String):void { var lineCount:int = textLines.length; for(var i:int = 0; i < lineCount; i++) { var line:TextLine = textLines[i]; if(textAlign == TEXT_ALIGN_CENTER) { line.x = (width - line.width) / 2; } else if(textAlign == TEXT_ALIGN_RIGHT) { line.x = width - line.width; } else { line.x = 0; } } } } } ",12522,False,2461.804331009107,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.validators.supportClasses { import flash.globalization.NationalDigitsType; import flash.globalization.NumberFormatter; import mx.core.mx_internal; import mx.validators.NumberValidatorDomainType; import mx.validators.ValidationResult; import spark.formatters.CurrencyFormatter; import spark.formatters.NumberFormatter; import spark.globalization.LastOperationStatus; import spark.globalization.supportClasses.GlobalizationBase; import spark.validators.supportClasses.GlobalizationUtils; import spark.validators.supportClasses.GlobalizationValidatorBase; use namespace mx_internal; /** * The NumberValidatorBase class contains all the common functionality that is * required by the NumberValidator and * CurrencyValidator classes. * * @mxml * *

The <s:NumberValidator> tag * inherits all of the tag attributes of its superclass, * and adds the following tag attributes:

* *
 *  <s:NumberValidatorBase
 *    Properties
 *    allowNegative=""true""
 *    decimalPointCountError=""The decimal separator can only occur once.""
 *    decimalSeparator=""locale specified string or customized by user.""
 *    digitsType=""locale specified string or customized by user.""
 *    domain=""real""
 *    fractionalDigits=""locale specified string or customized by user.""
 *    fractionalDigitsError=""The amount entered has too many digits beyond the decimal point.""
 *    greaterThanMaxError=""The number entered is too large.""
 *    groupingSeparator=""locale specified string or customized by user.""
 *    invalidCharError=""The input contains invalid characters.""
 *    invalidFormatCharsError=""One of the formatting parameters is invalid.""
 *    lessThanMinError=""The amount entered is too small.""
 *    localeUndefinedError=""Locale is undefined.""
 *    maxValue=""NaN""
 *    minValue=""NaN""
 *    negativeError=""The amount may not be negative.""
 *    negativeSymbolError=""The negative symbol is repeated or not in right place.""
 *    notAnIntegerError=""The number must be an integer.""
 *    parseError=""The input string could not be parsed.""
 *  />
 *  
* * @see spark.formatters.supportClasses.NumberFormatterBase * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class NumberValidatorBase extends GlobalizationValidatorBase { include ""../../core/Version.as""; //-------------------------------------------------------------------------- // // Class Constants // //-------------------------------------------------------------------------- private static const ALLOW_NEGATIVE:String = ""allowNegative""; private static const DECIMAL_SEPARATOR:String = ""decimalSeparator""; private static const DIGITS_TYPE:String = ""digitsType""; private static const FRACTIONAL_DIGITS:String = ""fractionalDigits""; private static const GROUPING_SEPARATOR:String = ""groupingSeparator""; private static const NEGATIVE_SYMBOL:String = ""negativeSymbol""; // Used by inheritors. mx_internal static const NUMBER_VALIDATOR_TYPE:int = 1; mx_internal static const CURRENCY_VALIDATOR_TYPE:int = 2; private static const NEGATIVE_SYMBOLS:String = ""-"" + String.fromCharCode(0x2212, 0xFE63, 0xFF0D); mx_internal static const VALID_CHARS:String = DECIMAL_DIGITS + ""("" + "")"" + NEGATIVE_SYMBOLS; // Follows flash.globalization limit. private static const PATTERN_LENGTH_LIMIT:int = 10; private static const DECIMAL_SEP_STD:String = "".""; /** * @private * A String containing the decimal digits 0 through 9. * */ mx_internal static const DECIMAL_DIGITS:String = ""0123456789""; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function NumberValidatorBase() { super(); // Previously allowNegative was an object. If it was null, the default // value was loaded from resource manager in the setter. But now it // is a boolean. Hence load it explicitly. _allowNegative = allowNegativeOverride = resourceManager.getBoolean( ""validators"", ""allowNegative""); _domain = NumberValidatorDomainType.REAL; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Underlying working instance of flash.globalizaiton.NumberFormatter or * CurrencyFormatter class. * * Because it can be either type and they don't have common base except * Object, it is defined as Object. */ private var _g11nWorkingInstance:Object = null; /** * @private * If the g11nWorkingInstance has not been defined. Call * ensureStyleSource to ensure that there is a styleParent. If there is * not a style parent, then this instance will be added as a style client * to the topLevelApplication. As a side effect of this, the styleChanged * method will be called and if there is a locale style defined for the * topLevelApplication, the createWorkingInstance method will be * executed creating a g11nWorkingInstance. */ mx_internal function get g11nWorkingInstance ():Object { if (!_g11nWorkingInstance) ensureStyleSource(); return _g11nWorkingInstance; } mx_internal function set g11nWorkingInstance (sparkFormatter:Object): void { _g11nWorkingInstance = sparkFormatter; } //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- //---------------------------------- // lastOperationStatus //---------------------------------- [Bindable(""change"")] /** * @inheritDoc * * @see spark.Globalization.LastOperationStatus * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ override public function get lastOperationStatus():String { return g11nWorkingInstance ? g11nWorkingInstance.lastOperationStatus : fallbackLastOperationStatus; } //---------------------------------- // useFallback //---------------------------------- [Bindable(""change"")] /** * @private */ override mx_internal function get useFallback():Boolean { return g11nWorkingInstance.useFallback; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // allowNegative //---------------------------------- /** * @private * Storage for the allowNegative property. */ private var _allowNegative:Boolean; /** * @private */ protected var allowNegativeOverride:Boolean; [Inspectable(category=""General"", defaultValue=""true"")] [Bindable(""change"")] /** * Specifies whether negative numbers are permitted. * Valid values are true or false. * * @default true * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get allowNegative():Boolean { return _allowNegative; } public function set allowNegative(value:Boolean):void { allowNegativeOverride = value; _allowNegative = value; update(); } //---------------------------------- // decimalSeparator //---------------------------------- [Bindable(""change"")] /** * The decimal separator character used for validating numbers that have * a decimal part. * *

This property is initially set based on the locale style of the * validator object.

* *

The default value is dependent on the locale and operating * system.

* * @throws TypeError if this property is assigned a null value. * * @see #validate() * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get decimalSeparator():String { return getBasicProperty(properties, DECIMAL_SEPARATOR); } public function set decimalSeparator(value:String):void { setBasicProperty(properties, DECIMAL_SEPARATOR, value); } //---------------------------------- // digitsType //---------------------------------- [Bindable(""change"")] /** * Defines the set of digit characters to be used when * validating numbers. * *

Different languages and regions use different sets of * characters to represent the * digits 0 through 9. This property defines the set of digits * to be used.

* *

The value of this property represents the Unicode value for * the zero digit of a decimal digit set. * The valid values for this property are defined in the * NationalDigitsType class.

* *

The default value is dependent on the locale and operating * system.

* * @see flash.globalization.NationalDigitsType * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get digitsType():uint { return getBasicProperty(properties, DIGITS_TYPE); } public function set digitsType(value:uint):void { setBasicProperty(properties, DIGITS_TYPE, value); } //---------------------------------- // domain //---------------------------------- /** * @private * Storage for the domain property. */ private var _domain:String; /** * @private */ protected var domainOverride:String = ""real""; [Inspectable(category=""General"", enumeration=""int,real"", defaultValue=""real"")] [Bindable(""change"")] /** * Type of number to be validated. * Permitted values are ""real"" and ""int"". * *

In ActionScript, you can use the following constants to set this * property: * NumberValidatorDomainType.REAL or * NumberValidatorDomainType.INT.

* * @default ""real"" * * @see #NumberValidatorDomainType * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get domain():String { return _domain; } /** * @private */ public function set domain(value:String):void { domainOverride = value; if (!value) { _domain = resourceManager.getString( ""validators"", ""numberValidatorDomain""); } else if ((value != NumberValidatorDomainType.INT) && (value != NumberValidatorDomainType.REAL)) { throw new ArgumentError(); } else { _domain = value; } update(); } //---------------------------------- // fractionalDigits //---------------------------------- [Bindable(""change"")] [Inspectable(category=""General"", minValue=""0"")] /** * The maximum number of digits that can appear after the decimal * separator. * *

The default value is dependent on the locale and operating * system.

* * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get fractionalDigits():int { return getBasicProperty(properties, FRACTIONAL_DIGITS); } public function set fractionalDigits(value:int):void { setBasicProperty(properties, FRACTIONAL_DIGITS, value); } //---------------------------------- // groupingSeparator //---------------------------------- [Bindable(""change"")] /** * The character or string used for the grouping separator. * *

The value of this property is used as the grouping * separator when validating numbers. This * property is initially set based on the locale that is selected * when the validator object is constructed.

* * @throws TypeError if this property is assigned a null value. * *

The default value is dependent on the locale and operating * system.

* * @see #validate() * @see #groupingPattern * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get groupingSeparator():String { return getBasicProperty(properties, GROUPING_SEPARATOR); } public function set groupingSeparator(value:String):void { setBasicProperty(properties, GROUPING_SEPARATOR, value); } //---------------------------------- // maxValue //---------------------------------- /** * @private * Storage for the maxValue property. */ private var _maxValue:Number; /** * @private */ protected var maxValueOverride:Number; [Inspectable(category=""General"", defaultValue=""null"")] [Bindable(""change"")] /** * Maximum value for a valid number. A value of NaN means there is no * maximum. * * @default NaN * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get maxValue():Number { return _maxValue; } /** * @private */ public function set maxValue(value:Number):void { maxValueOverride = value; _maxValue = value; update(); } //---------------------------------- // minValue //---------------------------------- /** * @private * Storage for the minValue property. */ private var _minValue:Number; /** * @private */ protected var minValueOverride:Number; [Inspectable(category=""General"", defaultValue=""null"")] [Bindable(""change"")] /** * Minimum value for a valid number. A value of NaN means there is no * minimum. * * @default NaN * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get minValue():Number { return _minValue; } public function set minValue(value:Number):void { minValueOverride = value; _minValue = value; update(); } //---------------------------------- // negativeSymbol //---------------------------------- [Bindable(""change"")] /** * The negative symbol to be used when validating negative values. * *

This symbol is used when validating a negative number. * This is read-only property as not all operating systems allow * customizing of this property.

* *

This property is set to a default value specified by the locale.

* * @see #negativeNumberFormat * @see #validate() * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get negativeSymbol():String { return getBasicProperty(properties, NEGATIVE_SYMBOL); } //-------------------------------------------------------------------------- // // Properties: Errors // //-------------------------------------------------------------------------- //---------------------------------- // decimalPointCountError //---------------------------------- /** * @private * Storage for the decimalPointCountError property. */ private var _decimalPointCountError:String; /** * @private */ protected var decimalPointCountErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the decimal separator character occurs more than * once. * * @default ""The decimal separator can occur only once."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get decimalPointCountError():String { return _decimalPointCountError; } public function set decimalPointCountError(value:String):void { if (decimalPointCountErrorOverride && (decimalPointCountErrorOverride == value)) return; decimalPointCountErrorOverride = value; _decimalPointCountError = value ? value : resourceManager.getString(""validators"", ""decimalPointCountError""); update(); } //---------------------------------- // fractionalDigitsError //---------------------------------- /** * @private * Storage for the fractionalDigitsError property. */ private var _fractionalDigitsError:String; /** * @private */ protected var fractionalDigitsErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when fraction digits exceeds the value specified * by the fractionalDigits property. * * @default ""The amount entered has too many digits beyond the decimal * point."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get fractionalDigitsError():String { return _fractionalDigitsError; } public function set fractionalDigitsError(value:String):void { if (fractionalDigitsErrorOverride && (fractionalDigitsErrorOverride == value)) return; fractionalDigitsErrorOverride = value; _fractionalDigitsError = value ? value : resourceManager.getString(""validators"", ""fractionalDigitsError""); update(); } //---------------------------------- // greaterThanMaxError //---------------------------------- /** * @private * Storage for the exceedsMaxError property. */ private var _greaterThanMaxError:String; /** * @private */ protected var greaterThanMaxErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value exceeds the maxValue property. * * @default ""The number entered is too large."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get greaterThanMaxError():String { return _greaterThanMaxError; } /** * @private */ public function set greaterThanMaxError(value:String):void { if (greaterThanMaxErrorOverride && (greaterThanMaxErrorOverride == value)) return; greaterThanMaxErrorOverride = value; _greaterThanMaxError = value ? value : resourceManager.getString(""validators"", ""exceedsMaxErrorNV""); update(); } //---------------------------------- // invalidCharError //---------------------------------- /** * @private * Storage for the invalidCharError property. */ private var _invalidCharError:String; /** * @private */ protected var invalidCharErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value contains invalid characters. * * @default ""The input contains invalid characters."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get invalidCharError():String { return _invalidCharError; } /** * @private */ public function set invalidCharError(value:String):void { if (invalidCharErrorOverride && (invalidCharErrorOverride == value)) return; invalidCharErrorOverride = value; _invalidCharError = value ? value : resourceManager.getString(""validators"", ""invalidCharError""); update(); } //---------------------------------- // invalidFormatCharsError //---------------------------------- /** * @private * Storage for the invalidFormatCharsError property. */ private var _invalidFormatCharsError:String; /** * @private */ protected var invalidFormatCharsErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value contains invalid format characters, which * means that it contains a digit or minus sign (-) as a separator * character, or it contains two or more consecutive separator characters. * * @default ""One of the formatting parameters is invalid."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get invalidFormatCharsError():String { return _invalidFormatCharsError; } public function set invalidFormatCharsError(value:String):void { if (invalidFormatCharsErrorOverride && (invalidFormatCharsErrorOverride == value)) return; invalidFormatCharsErrorOverride = value; _invalidFormatCharsError = value ? value : resourceManager.getString(""validators"", ""invalidFormatCharsError""); update(); } //---------------------------------- // lessThanMinError //---------------------------------- /** * @private * Storage for the lowerThanMinError property. */ private var _lessThanMinError:String; /** * @private */ protected var lessThanMinErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value is less than the minValue. * * @default ""The amount entered is too small."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get lessThanMinError():String { return _lessThanMinError; } public function set lessThanMinError(value:String):void { if (lessThanMinErrorOverride && (lessThanMinErrorOverride == value)) return; lessThanMinErrorOverride = value; _lessThanMinError = value ? value : resourceManager.getString(""validators"", ""lowerThanMinError""); update(); } //---------------------------------- // localeUndefinedError //---------------------------------- private var _localeUndefinedError:String; /** * @private */ protected var localeUndefinedErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the locale is undefined or is not available. * * @default ""Locale is undefined."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get localeUndefinedError():String { return _localeUndefinedError; } public function set localeUndefinedError(value:String):void { if (localeUndefinedErrorOverride && (localeUndefinedErrorOverride == value)) return; localeUndefinedErrorOverride = value; _localeUndefinedError = value ? value : resourceManager.getString(""validators"", ""localeUndefinedError""); update(); } //---------------------------------- // negativeError //---------------------------------- /** * @private * Storage for the negativeError property. */ private var _negativeError:String; /** * @private */ protected var negativeErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the value is negative and the * allowNegative property is false. * * @default ""The amount may not be negative."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get negativeError():String { return _negativeError; } public function set negativeError(value:String):void { if (negativeErrorOverride && (negativeErrorOverride == value)) return; negativeErrorOverride = value; _negativeError = value ? value : resourceManager.getString(""validators"", ""negativeError""); update(); } //---------------------------------- // negativeSymbolError //---------------------------------- /** * @private * Storage for the negativeSymbolError property. */ private var _negativeSymbolError:String; /** * @private */ protected var negativeSymbolErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the negative symbol is repeated or is in wrong place. * * @default ""The negative symbol is repeated or not in right place."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get negativeSymbolError():String { return _negativeSymbolError; } public function set negativeSymbolError(value:String):void { if (negativeSymbolErrorOverride && (negativeSymbolErrorOverride == value)) return; negativeSymbolErrorOverride = value; _negativeSymbolError = value ? value : resourceManager.getString(""validators"", ""negativeSymbolError""); update(); } //---------------------------------- // notAnIntegerError //---------------------------------- /** * @private * Storage for the integerError property. */ private var _notAnIntegerError:String; /** * @private */ protected var notAnIntegerErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when the number must be an integer, as defined * by the domain property. * * @default ""The number must be an integer."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get notAnIntegerError():String { return _notAnIntegerError; } public function set notAnIntegerError(value:String):void { if (notAnIntegerErrorOverride && (notAnIntegerErrorOverride == value)) return; notAnIntegerErrorOverride = value; _notAnIntegerError = value ? value : resourceManager.getString(""validators"", ""integerError""); update(); } //---------------------------------- // parseError //---------------------------------- private var _parseError:String; /** * @private */ protected var parseErrorOverride:String; [Inspectable(category=""Errors"", defaultValue=""null"")] [Bindable(""change"")] /** * Error message when number could not be parsed. * * @default ""The input string could not be parsed."" * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get parseError():String { return _parseError; } /** * @private */ public function set parseError(value:String):void { if (parseErrorOverride && (parseErrorOverride == value)) return; parseErrorOverride = value; _parseError = value ? value : resourceManager.getString(""validators"", ""parseError""); update(); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Create underlying formatter object for currency or number validator. * This method has the common code that is needed by both currency and * number validator object's createWorkingInstance(). * *

Create locale specific formatter object using localeStyle property. * If localeStyle is null, this method sets fallbackLastOperationStatus to * LOCALE_UNDEFINED_ERROR and returns. * If localeStyle is specified and fallback is enforced, then fallback * formatter object is created using ""en-US"" locale. Otherwise creates * the flash.globalization formatter. The formatter properties are updated * with the user overriden values.

* * @param validatorType An integer specifying currency or number validator. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 * */ mx_internal function createWorkingInstanceCore(validatorType:int):void { if (validatorType == NUMBER_VALIDATOR_TYPE) g11nWorkingInstance = new spark.formatters.NumberFormatter(); else if (validatorType == CURRENCY_VALIDATOR_TYPE) g11nWorkingInstance = new spark.formatters.CurrencyFormatter(); if (!g11nWorkingInstance) { throw new Error(""Internal failure: "" + ""spark formatter creation failure.""); } g11nWorkingInstance.enforceFallback = enforceFallback; g11nWorkingInstance.setStyle(""locale"", localeStyle); if (g11nWorkingInstance.lastOperationStatus != LastOperationStatus.UNSUPPORTED_ERROR) { properties = g11nWorkingInstance propagateBasicProperties(g11nWorkingInstance); return; } } /** * @private * Return the actual locale id name. * *

This method gets the actual locale id name from the internal * formatter object. If the formatter object is not available, returns * ""en-US"" as the ultimate fallback locale id name.

* * @param validatorType int having the validator type: currency or number * @returns String Actual locale id name * */ mx_internal function getActualLocaleIDName(validatorType:int):String { if (g11nWorkingInstance) { return (validatorType == NUMBER_VALIDATOR_TYPE) ? (g11nWorkingInstance as spark.formatters.NumberFormatter).actualLocaleIDName : (g11nWorkingInstance as spark.formatters.CurrencyFormatter).actualLocaleIDName; } // Flex binding allows a situation of getting actual locale id name // even before createWorkingInstance() is called. else { fallbackLastOperationStatus = LastOperationStatus.LOCALE_UNDEFINED_ERROR; return undefined; } } /** * @private * get the index of first digit. */ mx_internal function indexOfFirstDigit(input:String, len:int, start:int=0):int { if (!input || !len) return -1; for (var i:int = start; i < len; i++) { var c0:int = input.charCodeAt(i); var c32:int = processSurrogates(input, c0, i, len); if (c32 == -1) return -1; if (isDigit(c32)) return i; if (c0 != c32) i++; // surrogate found. index increment for lower surrogate. } return -1; } /** * @private * get the index of last digit. */ mx_internal function indexOfLastDigit(input:String, len:int, end:int):int { if (!input || !len) return -1; for (var i:int = end; i >= 0; i--) { var c0:int = input.charCodeAt(i); var c32:int = processSurrogates(input, c0, i, len); if (c32 == -1) return -1; if (c0 != c32) i--; // surrogate found. index decrement for lower surrogate. if (isDigit(c32)) return i; } return -1; } /** * @private */ mx_internal function inputHasMultipleNegativeSymbols(input:String):Boolean { if (!input) return false; var nflag:Boolean = false; var gflag:Boolean = false; var i:int = 0; var c:String; if (negativeSymbol == decimalSeparator) { nflag = true; } else { for (i = 0; i < NEGATIVE_SYMBOLS.length; i++) { c = NEGATIVE_SYMBOLS.charAt(i); if (decimalSeparator == c) { nflag = true; break; } } } if (negativeSymbol == groupingSeparator) { gflag = true } else { for (i = 0; i < NEGATIVE_SYMBOLS.length; i++) { c = NEGATIVE_SYMBOLS.charAt(i); if (groupingSeparator == c) { gflag = true; break; } } } if (!nflag && !gflag && (input.indexOf(negativeSymbol) != input.lastIndexOf(negativeSymbol))) { return true; } var nsymbols:String = NEGATIVE_SYMBOLS + negativeSymbol; var ncount:int = 0; for (i = 0; i < input.length; i++) { c = input.charAt(i); if (nsymbols.indexOf(c) != -1) ncount++; } if (!gflag) { if (!nflag) { if (ncount > 1) return true; } else { if (ncount > 2) return true; } } return false; } /** * @private */ mx_internal function inputHasNegativeSymbol(input:String):Boolean { if (!input) return false; if (input.indexOf(negativeSymbol) != -1) return true; for (var i:int = 0; i < input.length; i++) { var c:String = input.charAt(i); if (NEGATIVE_SYMBOLS.indexOf(c) != -1) return true; } return false; } /** * @private * Check if it is a digit.. */ private function isDigit(codepoint:int):Boolean { if (GlobalizationUtils.isDigit(codepoint)) return true; // Adding 9 may not be right always. But there is no way for user to // communicate the highest digit. if ((codepoint >= digitsType) && (codepoint <= digitsType + 9 )) return true; return false; } /** * @private */ mx_internal function isNegativeSymbol(input:String):Boolean { if (!input) return false; if (input == negativeSymbol) return true; for (var i:int = 0; i < NEGATIVE_SYMBOLS.length; i++) { var c:String = NEGATIVE_SYMBOLS.charAt(i); if (input == c) return true; } return false; } /** * @private * Load the error strings overrides. */ mx_internal function loadChangedResources():void { decimalPointCountError = decimalPointCountErrorOverride; greaterThanMaxError = greaterThanMaxErrorOverride; notAnIntegerError = notAnIntegerErrorOverride; invalidCharError = invalidCharErrorOverride; invalidFormatCharsError = invalidFormatCharsErrorOverride; lessThanMinError = lessThanMinErrorOverride; negativeError = negativeErrorOverride; negativeSymbolError = negativeSymbolErrorOverride; fractionalDigitsError = fractionalDigitsErrorOverride; parseError = parseErrorOverride; localeUndefinedError = localeUndefinedError; } private function inputHasNoDigits(input:String):Boolean { if (!input) return false; for (var i:int; i < input.length; i++) { var c0:int = input.charCodeAt(i); var c1:int = processSurrogates(input, c0, i, input.length); if (c1 == -1) continue; if (c0 != c1) i++; if (isDigit(c1)) return false; } return true; } /** * @private */ mx_internal function processSurrogates(input:String, c0:int, index:int, len:int):int { var j:int = 0; var c1:int; if (GlobalizationUtils.isLeadingSurrogate(c0)) { j = index + 1; if (j < len) { c1 = input.charCodeAt(j); if (GlobalizationUtils.isTrailingSurrogate(c1)) c0 = GlobalizationUtils.surrogateToUTF32(c0, c1); else return -1; } else return -1; } else if (GlobalizationUtils.isTrailingSurrogate(c0)) { j = index - 1; if (j >= 0) { c1 = input.charCodeAt(j); if (GlobalizationUtils.isLeadingSurrogate(c1)) c0 = GlobalizationUtils.surrogateToUTF32(c1, c0); else return -1; } else return -1; } return c0; } /** * @private * Validate the number string portion after the decimal point. * *

Checks that there are no errors in the number string after the * decimal. Example errors could be having a grouping separator or using an * invalid character like non-numeral after the decimal. If * there are any such errors, this method reports ""invalidCharError"" and * returns false. Otherwise, returns true.

* * @param input Input string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function validateDecimalString(input:String, baseField:String, results:Array, negPosLeft:Boolean):Boolean { if (!input) return true; var dindex:int; if (negPosLeft) dindex = input.lastIndexOf(decimalSeparator); else dindex = input.indexOf(decimalSeparator); var c:String; var i:int; var c0:int; var c1:int; if (dindex == -1) return true; for (i = input.length; i > dindex; i--) { c0 = input.charCodeAt(i); c1 = processSurrogates(input, c0, i, eindex); if (c1 == -1) return false; //illegal surrogate if (isDigit(c1)) break; if (c0 != c1) i--; // digit was surrogate. increment string index. } var eindex:int = i; i = dindex + decimalSeparator.length; for (; i < eindex; i++) { c0 = input.charCodeAt(i); c1 = processSurrogates(input, c0, i, eindex); if ((c1 != -1) && isDigit(c1)) { if (c0 != c1) i++; // digit was surrogate. increment string index. continue; } else { results.push(new ValidationResult( true, baseField, ""invalidChar"", invalidCharError)); return false; } } return true; } /** * @private * Check if a number has correct number of fraction digits. * *

This method validates if a decimal number has correct number of * fraction digits as specified by the fractionalDigits * property. It also checks if a number is supposed to be integer, based * on the domain property. For fraction digits error, it * reports the ""fractionalDigitsError"" message as specified in the * validator resources bundle. For integer error it reports the * ""integerError"" message. If there is an error, * this method returns false. Otherwise returns * true.

* * @param input Input Number string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function validateFractionPart(input:String, decimalSeparatorIndex:int, baseField:String, results:Array):Boolean { if (!input) return true; // Make sure that there aren't too many digits after the decimal point: // if domain is int there should be none, // otherwise there should be no more than specified by fractionalDigits. // The input string ALWAYS contains . as decimalseparator as, the caller // converts number obtained from NumberFormatter.parseNumber() to string // and then sends. const len:int = input.length; if (decimalSeparatorIndex != -1) { var numDigitsAfterDecimal:Number = 0; // we only have a '.' if (input == decimalSeparator) { results.push(new ValidationResult( true, baseField, ""invalidChar"", invalidCharError)); return false; } var i:int = decimalSeparatorIndex + decimalSeparator.length; // There may not be any digits after the decimal // if domain is int. var c0:int = input.charCodeAt(i); var c32:int = processSurrogates(input, c0, i, len); if (c32 == -1) { results.push(new ValidationResult( true, baseField, ""invalidChar"", invalidCharError)); return false; } if ((i < len) && isDigit(c32)) { if (domain == NumberValidatorDomainType.INT) { results.push(new ValidationResult( true, baseField,""integer"", notAnIntegerError)); return false; } } for (;i < len; i++) { c0 = input.charCodeAt(i); c32 = processSurrogates(input, c0, i, len); if (c32 == -1) { results.push(new ValidationResult( true, baseField, ""invalidChar"", invalidCharError)); return false; } if (c0 != c32) i++; // surrogate found. increment index of lower surrogate. ++numDigitsAfterDecimal; // break at ) or - or currency string when validatng fractions. if (!isDigit(c32)) break; // Make sure fractionalDigits is not exceeded. if (fractionalDigits != -1 && numDigitsAfterDecimal > fractionalDigits) { results.push(new ValidationResult( true, baseField, ""fractionalDigits"", fractionalDigitsError)); return false; } } } return true; } /** * @private * Check if a number string contains invalid characters. * *

This method validates if a number string has any characters other * than the caller specified valid characters. Valid characters for numbers * and currency comprise of digits, decimal separator, grouping separator, * negative format characters, currency ISO code, currency symbol and white * space. If any other character is found, then this method returns * false. Otherwise returns true.

* * @param input String representation of number to be validated. * @param len int specifying the length of input * @param validChars String containing all valid characters. * * @return Boolean true if no error otherwise false. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ // detect if invalid characters are present in input. Caller supplies the // valid characters. // TODO: The code to check for valid surrogates is repeated in many methods. // See if this can be optimized. mx_internal function validateInputCharacters(input:String, len:int, validChars:String):Boolean { if (!input) return true; for (var i:int = 0; i < len; i++) { const c:String = input.charAt(i); if (validChars.indexOf(c) == -1) { var c0:int = c.charCodeAt(0); var c32:int = processSurrogates(input, c0, i, len); if (c32 == -1) return true; else if (c0 != c32) // surrogate. increment string index. i++; if (isDigit(c0)) continue; if (GlobalizationUtils.isWhiteSpace(c0)) continue; return true; } } return false; } /** * @private * Check if input number string has any format or negative symbol errors. * *

This method validates if an input number string has right format * and does not have multiple negative symbols. * If there is an error, this method returns false. Otherwise * returns true.

* * @param input Input Number string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ // check some common errors. mx_internal function validateNumberFormat(input:String, results:Array, baseField:String):Boolean { if (!input) return true; const len:int = input.length; var c:String; if (input.charAt(0) == ""("") { // Make sure the last character is a closed parenthesis. if (input.charAt(len - 1) != "")"") { results.push(new ValidationResult( true, baseField, ""invalidFormatChars"", invalidFormatCharsError)); return false; } } else if (input.charAt(len - 1) == "")"") { // Make sure the last character is a closed parenthesis. if (input.charAt(0) != ""("") { results.push(new ValidationResult( true, baseField, ""invalidFormatCharsError"", invalidFormatCharsError)); return false; } } if (decimalSeparator == groupingSeparator) { results.push(new ValidationResult( true, baseField, ""invalidFormatChars"", invalidFormatCharsError)); return false; } else if (inputHasNoDigits(input)) { results.push(new ValidationResult( true, baseField, ""parseError"", parseError)); return false; } else if (inputHasMultipleNegativeSymbols(input)) { results.push(new ValidationResult( true, baseField, ""negativeSymbol"", negativeSymbolError)); return false; } return true; } /** * @private * Check if input number can be negative depending on allowNegative * property. * *

Checks if input number can be negative based on the * allowNegative property. If allowNegative is * false and number is negative, this method reports ""negativeError"" and * returns false. Otherwise, returns true.

* * @param inputNum Input Number string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function validateNumberNegativity(inputNum:Number, baseField:String, results:Array):Boolean { if (inputNum < 0) { // Check if negative input is allowed. if (!allowNegative) { results.push(new ValidationResult( true, baseField, ""negative"", negativeError)); return false; } } return true; } /** * @private * Check if a number is in a range specified by the user. * *

This method validates if a number is in the range specified by the * user. The minValue and maxValue properties define the range. If the * number is not in the range, then this method reports either * ""lowerThanMinError"" or ""exceedsMaxError"". If there is a range error, * this returns false. Otherwise returns * true.

* * @param num Input Number string to be checked. * @param baseField The field name of the Object being validated. * @param results Array holding the ValidationResult objects. * * @return Boolean true if no error otherwise false. * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function validateNumberRange(num:Number, baseField:String, results:Array):Boolean { const maxValue:Number = Number(maxValue); const minValue:Number = Number(minValue); if (!isNaN(minValue) || !isNaN(maxValue)) { if (!isNaN(minValue) && (num < minValue)) { results.push(new ValidationResult( true, baseField, ""lowerThanMin"", lessThanMinError)); return false; } if (!isNaN(maxValue) && (num > maxValue)) { results.push(new ValidationResult( true, baseField, ""exceedsMax"", greaterThanMaxError)); return false; } } return true; } } } ",12348,True,2579.4416622840163,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar SqlBase; tokens { DELIMITER } @header { using Qsi.Data; using Qsi.Tree; using Qsi.Utilities; } singleStatement : statement EOF ; standaloneExpression : expression EOF ; standaloneRoutineBody : routineBody EOF ; statement /*** * ATHENA DDL * * @athena (Amazon Athena DDL Reference)[https://docs.aws.amazon.com/athena/latest/ug/language-reference.html] * @hive (HiveQL DDL Reference)[https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL] */ /********************** * * * * * Database DDL * * * * * **********************/ /** * Create Database * * @athena https://docs.aws.amazon.com/athena/latest/ug/create-database.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateDatabaseCreateDatabase */ : CREATE (REMOTE)? (DATABASE | SCHEMA) (IF NOT EXISTS)? databaseName=identifier[null] (COMMENT comment=string)? (LOCATION location=string)? (MANAGEDLOCATION managedLocation=string)? (WITH DBPROPERTIES dbProperties=stringProperties)? #createDatabase /** * Drop Database * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropDatabase */ | DROP (DATABASE | SCHEMA) (IF EXISTS)? databaseName=qualifiedName (RESTRICT | CASCADE)? #dropDatabase /** * Database Set DB Properties * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-database-set-dbproperties.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterDatabase */ | ALTER (DATABASE | SCHEMA) databaseName=qualifiedName SET DBPROPERTIES dbProperties=stringProperties #setDbProperties /** * Database Set Owner * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Database Set Location * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Database Set Managed Location * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Use Database * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-UseDatabase * @notsupport Tested at 2021. 12. 20.s */ // | USE // databaseName=identifier[null] #useDatabase /********************** * * * * * Data Connector DDL * * * * * **********************/ /** * Create Connector * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateDataConnectorCreateConnector * @notsupport Not tested */ // Not Implemented /** * Drop Connector * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropConnector * @notsupport Not tested */ // Not Implemented /** * Connector Set DC Properties * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterConnector * @notsupport Not tested */ // Not Implemented /** * Connector Set URL * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterConnector * @notsupport Not tested */ // Not Implemented /** * Connector Set Owner * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterConnector * @notsupport Not tested */ // Not Implemented /********************** * * * * * Table DDL * * * * * **********************/ /** * Create Table * * @athena https://docs.aws.amazon.com/athena/latest/ug/create-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateTable */ | CREATE (TEMPORARY)? (EXTERNAL)? TABLE (IF NOT EXISTS)? tableName=qualifiedName ( '(' columnDefinition (',' columnDefinition)* ')' )? (COMMENT tableComment=string)? (PARTITIONED BY '(' columnDefinition (',' columnDefinition)* ')' )? ( CLUSTERED BY '(' identifier[null] (',' identifier[null])* ')' (SORTED BY (columnName=identifier[null] (ASC | DESC)? (',' columnName=identifier[null] (ASC | DESC)? )* ) )? INTO numBuckets=number BUCKETS )? ( SKEWED BY '(' columnName=identifier[null] (',' columnName=identifier[null])* ')' ON '(' '(' columnValue=string (',' columnValue=string)* ')' ( ',' '(' columnValue=string (',' columnValue=string)* ')' )* ')' (STORED AS DIRECTORIES)? )? ( ROW FORMAT rowFormat | STORED AS fileFormat | ROW FORMAT rowFormat STORED AS fileFormat | STORED BY storageHandlerClassName=string (WITH SERDEPROPERTIES serDeProperties=stringProperties)? )? (LOCATION location=string)? (TBLPROPERTIES tblProperties=stringProperties)? #createTable /** * Create Table As * * @athena https://docs.aws.amazon.com/athena/latest/ug/create-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateTable */ | CREATE (TEMPORARY)? (EXTERNAL)? TABLE (IF NOT EXISTS)? tableName=qualifiedName ( '(' columnDefinition (',' columnDefinition)* ')' )? (COMMENT tableComment=string)? (PARTITIONED BY '(' columnDefinition (',' columnDefinition)* ')' )? ( CLUSTERED BY '(' identifier[null] (',' identifier[null])* ')' (SORTED BY (columnName=identifier[null] (ASC | DESC)? (',' columnName=identifier[null] (ASC | DESC)? )* ) )? INTO numBuckets=number BUCKETS )? ( SKEWED BY '(' columnName=identifier[null] (',' columnName=identifier[null])* ')' ON '(' '(' columnValue=string (',' columnValue=string)* ')' ( ',' '(' columnValue=string (',' columnValue=string)* ')' )* ')' (STORED AS DIRECTORIES)? )? ( ROW FORMAT rowFormat | STORED AS fileFormat | ROW FORMAT rowFormat STORED AS fileFormat | STORED BY storageHandlerClassName=string (WITH SERDEPROPERTIES serDeProperties=stringProperties)? )? (LOCATION location=string)? (TBLPROPERTIES tblProperties=stringProperties)? AS query (WITH NO? DATA)? #createTableAs /** * Create TABLE LIKE * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateTable */ | CREATE (TEMPORARY)? (EXTERNAL)? TABLE (IF NOT EXISTS)? tableName=qualifiedName LIKE likeTableName=qualifiedName (LOCATION location=string) #createTableLike /** * Drop Table * * @athena https://docs.aws.amazon.com/athena/latest/ug/drop-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropTable */ | DROP TABLE (IF NOT EXISTS)? tableName=qualifiedName (PURGE)? #dropTable /** * Truncate Table * * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /** * Table Rename to * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Set Tbl Properties * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-set-tblproperties.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterTableProperties */ | ALTER TABLE tableName=qualifiedName SET TBLPROPERTIES tblProperties=stringProperties #setTblProperties /** * Table Set Serde * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table Set Serde Properties * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table Unset Serde Properties * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table Add Constraint * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table Clustered by * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Not Clustered * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Skewed by * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Set Skewed Location * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Not Skewed * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Not Stored * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table Not Stored as Directories * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Msck Repair Table * * @athena https://docs.aws.amazon.com/athena/latest/ug/msck-repair-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-RecoverPartitions(MSCKREPAIRTABLE) */ | MSCK (REPAIR)? TABLE tableName=qualifiedName (ADD | DROP | SYNC PARTITIONS) #repairTable /*************************** * * * * * Table/Partition DDL * * * * * ***************************/ /** * Table/Partition Set File Format * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table/Partition Touch * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table/Partition Compact * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table/Partition Concatenate * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Table/Partition Enable/Disable No Drop * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table/Partition Enable/Disable Offline * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table/Partition Update Columns * * @notsupport Tested at 2021. 12. 14. */ // Not Implemented /** * Table/Partition Set Location * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-set-location.html * @hive https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=82706445#LanguageManualDDL-AlterTable/PartitionLocation */ | ALTER TABLE tableName=qualifiedName (PARTITION partitionSpec=properties)? SET LOCATION location=string #setLocation /********************** * * * * * Partition DDL * * * * * **********************/ /** * Archive Partition * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Unarchive Partition * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Add Partitions * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-add-partition.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AddPartitions */ | ALTER TABLE tableName=qualifiedName ADD (IF NOT EXISTS)? ( PARTITION partitionSpec=properties (LOCATION location=string)? )+ #addPartitions /** * Rename Partition * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-rename-partition.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-RenamePartition */ | ALTER TABLE tableName=qualifiedName PARTITION from=properties RENAME TO PARTITION to=properties #renamePartition /** * Exchange Partition * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Drop Partition * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-drop-partition.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropPartitions */ | ALTER TABLE tableName=qualifiedName DROP (IF EXISTS)? PARTITION partitionSpec=properties (',' PARTITION partitionSpec=properties)* (IGNORE PROTECTION)? (PURGE)? #dropPartition // endregion /********************** * * * * * Column DDL * * * * * **********************/ /** * Change Column * @comment According to Reference1(AWS), CHANGE COLUMN is not supported in Athena, but works in test * test query: ""ALTER TABLE table_name CHANGE original_column changed_column int"" * @athena https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ChangeColumnName/Type/Position/Comment */ | ALTER TABLE tableName=qualifiedName (PARTITION properties)? CHANGE (COLUMN)? identifier[null] columnDefinition (FIRST | AFTER identifier[null])? (CASCADE | RESTRICT)? #changeColumn /** * Add Columns * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-add-columns.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-Add/ReplaceColumns */ | ALTER TABLE tableName=qualifiedName (PARTITION partitionSpec=properties)? ADD COLUMNS '(' columnDefinition (',' columnDefinition)* ')' (CASCADE|RESTRICT)? #addColumns /** * Replace Columns * * @athena https://docs.aws.amazon.com/athena/latest/ug/alter-table-replace-columns.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-Add/ReplaceColumns */ | ALTER TABLE tableName=qualifiedName (PARTITION partitionSpec=properties)? REPLACE COLUMNS '(' columnDefinition (',' columnDefinition)* ')' (CASCADE|RESTRICT)? #replaceColumns /********************** * * * * * View DDL * * * * * **********************/ /** * Create View * * @athena https://docs.aws.amazon.com/athena/latest/ug/create-view.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-CreateView */ | CREATE (OR REPLACE)? VIEW (IF NOT EXISTS)? viewName=qualifiedName ( columnName=identifier[null] (COMMENT columnComment=string)? (',' columnName=identifier[null] (COMMENT columnComment=string)? )* )? viewColumnAliases? (COMMENT viewComment=string)? (TBLPROPERTIES tblProperties=stringProperties)? AS query #createView /** * Drop View * * @athena https://docs.aws.amazon.com/athena/latest/ug/drop-view.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DropView */ | DROP VIEW (IF EXISTS)? viewName=qualifiedName #dropView /** * Set View Tbl Properties * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterViewProperties */ | ALTER VIEW viewName=qualifiedName SET TBLPROPERTIES tblProperties=stringProperties #setViewTblProperties /** * Alter View As Select * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AlterViewAsSelect */ | ALTER VIEW viewName=qualifiedName AS query #alterViewAsSelect /************************* * * * * * Materialized View DDL * * * * * *************************/ /** * Create Materialized View * * @notsupport Not tested */ // Not Implemented /** * Drop Materialized View * * @notsupport Not tested */ // Not Implemented /** * Alter Materialized View * * @notsupport Not tested */ // Not Implemented /************************* * * * * * Index DDL * * * * * *************************/ /** * Create Index * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Drop Index * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Alter Index * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /************************* * * * * * Macro DDL * * * * * *************************/ /** * Create Temporary Macro * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Drop Temporary Macro * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /************************* * * * * * Function DDL * * * * * *************************/ /** * Create Function * * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /** * Drop Function * * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /** * Reload Function * * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /************************* * * * * * Role DDL * * * * * *************************/ /** * Create Role * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Grant Role * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Revoke Role * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Drop Role * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Roles * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Role Grant * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Current Roles * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Set Role * * @notsupport Not tested */ // Not Implemented /** * Show Principals * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Grant privilege_type * * @notsupport Not tested */ // Not Implemented /** * Revoke privilege_type * * @notsupport Not tested */ // Not Implemented /** * Show Grant * * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /************************* * * * * * Show DDL * * * * * *************************/ /** * Show Databases * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-databases.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowDatabases */ | SHOW (DATABASES | SCHEMAS) (LIKE string)? #showDatabases /** * Show Connectors * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowConnectors * @notsupport Not tested */ // Not Implemented /** * Show Tables * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-tables.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowTables */ | SHOW TABLES (IN databaseName=identifier[null])? (string)? #showTables /** * Show Views * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-views.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowViews */ | SHOW VIEWS ( (IN | FROM) databaseName=identifier[null])? (LIKE string) #showViews /** * Show Materialized Views * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowMaterializedViews * @notsupport Not tested */ // Not Implemented /** * Show Partitions * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-partitions.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowPartitions */ | SHOW PARTITIONS tableName=qualifiedName (PARTITION properties)? (WHERE where=booleanExpression)? (ORDER BY sortItem (',' sortItem)*)? (LIMIT limit=INTEGER_VALUE)? #showPartitions /** * Show Table/Partition Extended * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowTable/PartitionExtended */ | SHOW TABLE EXTENDED ((IN | FROM) databaseName=qualifiedName)? LIKE string (PARTITION properties)? #showTableExtended /** * Show Table Properties * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-tblproperties.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowTableProperties */ | SHOW TBLPROPERTIES tableName=qualifiedName ( '(' string ')' )? #showTableProperties /** * Show Create Table * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-create-table.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowCreateTable */ | SHOW CREATE TABLE tableName=qualifiedName #showCreateTable /** * Show Indexes * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowIndexes * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Columns * * @athena https://docs.aws.amazon.com/athena/latest/ug/show-columns.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowColumns */ | SHOW COLUMNS (FROM | IN) tableName=qualifiedName ( (FROM | IN) databaseName=qualifiedName?) (LIKE string)? #showColumns /** * Show Functions * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowFunctions * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Locks * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowLocks * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Conf * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowConf * @notsupport Tested at 2021. 12. 16. */ // Not Implemented /** * Show Transactions * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowTransactions * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Show Compactions * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-ShowCompactions * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /************************* * * * * * Describe DDL * * * * * *************************/ /** * Describe Database * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DescribeDatabase * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * Describe Data Connector * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DescribeDataconnector * @notsupport Not tested */ // Not Implemented /** * Describe Table / View / MaterializedView / Column * * @athena https://docs.aws.amazon.com/athena/latest/ug/describe-table.html * @athena https://docs.aws.amazon.com/athena/latest/ug/describe-view.html * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-DescribeTable/View/MaterializedView/Column */ | (DESCRIBE | DESC) (EXTENDED | FORMATTED)? tableName=qualifiedName (PARTITION partitionSpec=properties)? ( columnName=identifier[null] ( '.' (fieldName=identifier[null] | '$elem$' | '$key$' | '$value$') )* )? #describeTable /************************* * * * * * Abort DDL * * * * * *************************/ /** * Abort Transactions * * @hive https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-AbortTransactions * @notsupport Not tested */ /*** * ATHENA DML * * @athena (Amazon Athena DML Reference)[https://docs.aws.amazon.com/athena/latest/ug/functions-operators-reference-section.html] * @presto (Presto SQL Syntax Refrence)[https://prestodb.io/docs/current/sql.html] */ /** * ALTER FUNCTION * * @presto https://prestodb.io/docs/current/sql/alter-function.html * @notsupport Use hive syntax */ // Not Implemented /** * ALTER SCHEMA * * @presto https://prestodb.io/docs/current/sql/alter-schema.html * @notsupport Use hive syntax */ // Not Implemented /** * ALTER TABLE * * @presto https://prestodb.io/docs/current/sql/alter-table.html * @notsupport Use hive syntax */ // Not Implemented /** * Analyze * * @presto https://prestodb.io/docs/current/sql/analyze.html * @notsupport Tested at 2021. 12. 20. */ // Not Implemented /** * Call * * @presto https://prestodb.io/docs/current/sql/call.html * @notsupport Tested at 2021. 12. 20. */ // Not Implemented /** * COMMIT * * @presto https://prestodb.io/docs/current/sql/commit.html * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemeneted /** * CREATE FUNCTION * * @presto https://prestodb.io/docs/current/sql/create-function.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE ROLE * * @presto https://prestodb.io/docs/current/sql/create-role.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE SCHEMA * * @presto https://prestodb.io/docs/current/sql/create-schema.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE TABLE * * @presto https://prestodb.io/docs/current/sql/create-table.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE TABLE AS * * @presto https://prestodb.io/docs/current/sql/create-table-as.html * @notsupport Use hive syntax */ // Not Implemented /** * CREATE VIEW * * @presto https://prestodb.io/docs/current/sql/create-view.html * @notsupport Use hive syntax */ // Not Implemented /** * DEALLOCATE PREPARE * * @athena https://docs.aws.amazon.com/athena/latest/ug/querying-with-prepared-statements.html * @presto https://prestodb.io/docs/current/sql/deallocate-prepare.html */ | DEALLOCATE PREPARE identifier[null] #deallocate /** * DELETE * * @presto https://prestodb.io/docs/current/sql/delete.html * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * DESCRIBE * * @presto https://prestodb.io/docs/current/sql/describe.html * @notsupport Use hive syntax */ // Not Implemented /** * DESCRIBE INPUT * * @presto https://prestodb.io/docs/current/sql/describe-input.html * @notsupport Use hive syntax */ // Not Implemented /** * DESCRIBE OUTPUT * * @presto https://prestodb.io/docs/current/sql/describe-output.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP FUNCTION * * @presto https://prestodb.io/docs/current/sql/drop-function.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP ROLE * * @presto https://prestodb.io/docs/current/sql/drop-role.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP SCHEMA * * @presto https://prestodb.io/docs/current/sql/drop-schema.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP TABLE * * @presto https://prestodb.io/docs/current/sql/drop-table.html * @notsupport Use hive syntax */ // Not Implemented /** * DROP VIEW * * @presto https://prestodb.io/docs/current/sql/drop-view.html * @notsupport Use hive syntax */ // Not Implemented /** * EXECUTE * * @athena https://docs.aws.amazon.com/athena/latest/ug/querying-with-prepared-statements.html * @presto https://prestodb.io/docs/current/sql/execute.html */ | EXECUTE identifier[null] (USING expression (',' expression)*)? #execute /** * EXPLAIN * * @athena https://docs.aws.amazon.com/athena/latest/ug/athena-explain-statement.html * @presto https://prestodb.io/docs/current/sql/explain.html */ | EXPLAIN VERBOSE? ('(' explainOption (',' explainOption)* ')')? statement #explain /** * EXPLAIN ANALYZE * * @athena https://docs.aws.amazon.com/athena/latest/ug/athena-explain-statement.html * @presto https://prestodb.io/docs/current/sql/explain-analyze.html */ | EXPLAIN ANALYZE VERBOSE? ('(' explainOption (',' explainOption)* ')')? statement #explainAnalyze /** * GRANT * * @presto https://prestodb.io/docs/current/sql/grant.html * @notsupport Use hive syntax */ // Not Implemented /** * GRANT ROLES * * @presto https://prestodb.io/docs/current/sql/grant-roles.html * @notsupport Use hive syntax */ // Not Implemented /** * INSERT * * @athena https://docs.aws.amazon.com/athena/latest/ug/insert-into.html * @presto https://prestodb.io/docs/current/sql/insert.html */ | INSERT INTO qualifiedName columnAliases? query #insertInto /** * PREPARE * * @athena https://docs.aws.amazon.com/athena/latest/ug/querying-with-prepared-statements.html * @presto */ | PREPARE identifier[null] FROM statement #prepare /** * RESET SESSION * * @presto https://prestodb.io/docs/current/sql/reset-session.html * @notsupport Use hive syntax */ // Not Implemented /** * REVOKE * * @presto https://prestodb.io/docs/current/sql/revoke.html * @notsupport Use hive syntax */ // Not Implemented /** * REVOKE ROLES * * @presto https://prestodb.io/docs/current/sql/revoke-roles.html * @notsupport Use hive syntax */ // Not Implemented /** * ROLLBACK * * @presto https://prestodb.io/docs/current/sql/rollback.html * @notsupport https://docs.aws.amazon.com/athena/latest/ug/unsupported-ddl.html */ // Not Implemented /** * SELECT * * @athena https://docs.aws.amazon.com/athena/latest/ug/select.html * @presto https://prestodb.io/docs/current/sql/select.html */ | query #statementDefault /** * SET ROLE * * @presto https://prestodb.io/docs/current/sql/set-role.html * @notsupport Use hive syntax */ // Not Implemented /** * SET SESSION * * @presto https://prestodb.io/docs/current/sql/set-session.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW CATALOGS * * @presto https://prestodb.io/docs/current/sql/show-catalogs.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW COLUMNS * * @presto https://prestodb.io/docs/current/sql/show-columns.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW CREATE FUNCTION * * @presto https://prestodb.io/docs/current/sql/show-create-function.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW CREATE TABLE * * @presto https://prestodb.io/docs/current/sql/show-create-table.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW CREATE VIEW * * @presto https://prestodb.io/docs/current/sql/show-create-view.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW FUNCTIONS * * @presto https://prestodb.io/docs/current/sql/show-functions.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW GRANTS * * @presto https://prestodb.io/docs/current/sql/show-grants.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW ROLE GRANTS * * @presto https://prestodb.io/docs/current/sql/show-role-grants.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW ROLES * * @presto https://prestodb.io/docs/current/sql/show-roles.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW SCHEMAS * * @presto https://prestodb.io/docs/current/sql/show-schemas.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW SESSION * * @presto https://prestodb.io/docs/current/sql/show-session.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW STATS * * @presto https://prestodb.io/docs/current/sql/show-stats.html * @notsupport Use hive syntax */ // Not Implemented /** * SHOW TABLES * * @presto https://prestodb.io/docs/current/sql/show-tables.html * @notsupport Use hive syntax */ // Not Implemented /** * START TRANSACTION * * @presto https://prestodb.io/docs/current/sql/start-transaction.html * @notsupport Use hive syntax */ // Not Implemented /** * USE * * @presto https://prestodb.io/docs/current/sql/use.html * @notsupport Use hive syntax */ // Not Implemented /** * VALUES * * @presto https://prestodb.io/docs/current/sql/values.html */ // Implemented in ""query"" /*** * Athena Only Statements */ /** * UNLOAD * * @athena https://docs.aws.amazon.com/athena/latest/ug/unload.html */ | UNLOAD '(' query ')' TO location=string WITH properties #unload ; query : with? queryNoWith ; with : WITH namedQuery (',' namedQuery)* ; //tableElement // : columnDefinition // | likeClause // ; columnDefinition : identifier[null] dataType (COMMENT comment=string)? ; //likeClause // : LIKE qualifiedName (optionType=(INCLUDING | EXCLUDING) PROPERTIES)? // ; rowFormat : DELIMITED (FIELDS TERMINATED BY string (ESCAPED BY string)?)? (COLLECTION ITEMS TERMINATED BY string)? (MAP KEYS TERMINATED BY string)? (LINES TERMINATED BY string)? (NULL DEFINED AS string)? | SERDE string (WITH SERDEPROPERTIES stringProperties)? ; fileFormat : SEQUENCEFILE | TEXTFILE | RCFILE | ORC | PARQUET | AVRO | JSONFILE | INPUTFORMAT string OUTPUTFORMAT string ; stringProperties : '(' stringProperty (',' stringProperty)* ')' ; stringProperty : string EQ string ; properties : '(' property (',' property)* ')' ; property : identifier[null] EQ expression ; //sqlParameterDeclaration // : identifier[null] type // ; //routineCharacteristics // : routineCharacteristic* // ; //routineCharacteristic // : LANGUAGE language // | determinism // | nullCallClause // ; //alterRoutineCharacteristics // : alterRoutineCharacteristic* // ; //alterRoutineCharacteristic // : nullCallClause // ; routineBody : returnStatement | externalBodyReference ; returnStatement : RETURN expression ; externalBodyReference : EXTERNAL (NAME externalRoutineName)? ; //language // : SQL // | identifier[null] // ; // //determinism // : DETERMINISTIC // | NOT DETERMINISTIC; // //nullCallClause // : RETURNS NULL ON NULL INPUT // | CALLED ON NULL INPUT // ; externalRoutineName : identifier[null] ; queryNoWith : queryTerm orderBy? limitOffsetTerm? ; limitOffsetTerm : offsetTerm limitTerm | offsetTerm | limitTerm ; offsetTerm : OFFSET rowCountTerm ROW? | OFFSET rowCountTerm ROWS ; limitTerm : LIMIT rowCountTerm | LIMIT ALL ; rowCountTerm : INTEGER_VALUE | parameterExpression ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm operator=(UNION | EXCEPT | INTERSECT) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | TABLE qualifiedName #table | VALUES expression (',' expression)* #inlineTable | '(' queryNoWith ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrdering=(FIRST | LAST))? ; querySpecification : SELECT setQuantifier? selectItem (',' selectItem)* fromTerm? whereTerm? groupByHavingTerm? ; fromTerm : FROM relation (',' relation)* ; whereTerm : WHERE where=booleanExpression ; groupByHavingTerm : GROUP BY setQuantifier? groupingElement (',' groupingElement)* HAVING having=booleanExpression | GROUP BY setQuantifier? groupingElement (',' groupingElement)* | HAVING having=booleanExpression ; //groupBy // : setQuantifier? groupingElement (',' groupingElement)* // ; groupingElement : groupingSet #singleGroupingSet | ROLLUP '(' (expression (',' expression)*)? ')' #rollup | CUBE '(' (expression (',' expression)*)? ')' #cube | GROUPING SETS '(' groupingSet (',' groupingSet)* ')' #multipleGroupingSets ; groupingSet : '(' (expression (',' expression)*)? ')' #multipleExpressionGroupingSet | expression #singleExpressionGroupingSet ; namedQuery : name=identifier[null] (columnAliases)? AS '(' query ')' ; setQuantifier : DISTINCT | ALL ; selectItem : expression (AS? identifier[null])? #selectSingle | qualifiedName '.' ASTERISK #selectAll | ASTERISK #selectAll ; relation : left=relation ( CROSS JOIN right=sampledRelation | joinType JOIN rightRelation=relation joinCriteria | NATURAL joinType JOIN right=sampledRelation ) #joinRelation | sampledRelation #relationDefault ; joinType : INNER? | LEFT OUTER? | RIGHT OUTER? | FULL OUTER? ; joinCriteria : ON booleanExpression | USING '(' identifier[null] (',' identifier[null])* ')' ; sampledRelation : aliasedRelation ( TABLESAMPLE sampleType '(' percentage=expression ')' )? ; sampleType : BERNOULLI | SYSTEM ; aliasedRelation : relationPrimary (AS? identifier[null] columnAliases?)? ; viewColumnAliases : '(' columnName+=identifier[null] (COMMENT string)? (',' columnName+=identifier[null] (COMMENT string)? )* ')' ; columnAliases : '(' identifier[null] (',' identifier[null])* ')' ; relationPrimary : qualifiedName #tableName | '(' query ')' #subqueryRelation | UNNEST '(' expression (',' expression)* ')' (WITH ORDINALITY)? #unnest | LATERAL '(' query ')' #lateral | '(' relation ')' #parenthesizedRelation ; expression : booleanExpression ; booleanExpression : valueExpression predicate[$valueExpression.ctx]? #predicated | NOT booleanExpression #logicalNot | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; // workaround for https://github.com/antlr/antlr4/issues/780 predicate[ParserRuleContext value] : comparisonOperator right=valueExpression #comparison | comparisonOperator comparisonQuantifier '(' query ')' #quantifiedComparison | NOT? BETWEEN lower=valueExpression AND upper=valueExpression #between | NOT? IN '(' expression (',' expression)* ')' #inList | NOT? IN '(' query ')' #inSubquery | NOT? LIKE pattern=valueExpression (ESCAPE escape=valueExpression)? #like | IS NOT? NULL #nullPredicate | IS NOT? DISTINCT FROM right=valueExpression #distinctFrom ; valueExpression : primaryExpression #valueExpressionDefault | valueExpression AT timeZoneSpecifier #atTimeZone | operator=(MINUS | PLUS) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS) right=valueExpression #arithmeticBinary | left=valueExpression CONCAT right=valueExpression #concatenation ; primaryExpression : NULL #nullLiteral | interval #intervalLiteral | identifier[null] string #typeConstructor | DOUBLE_PRECISION string #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | string #stringLiteral | BINARY_LITERAL #binaryLiteral | parameterExpression #parameter | POSITION '(' valueExpression IN valueExpression ')' #position | '(' expression (',' expression)+ ')' #rowConstructor | ROW '(' expression (',' expression)* ')' #rowConstructor | qualifiedName '(' ASTERISK ')' filter? over? #functionCall | qualifiedName '(' (setQuantifier? expression (',' expression)*)? orderBy? ')' filter? (nullTreatment? over)? #functionCall | identifier[null] '->' expression #lambda | '(' (identifier[null] (',' identifier[null])*)? ')' '->' expression #lambda | '(' query ')' #subqueryExpression // This is an extension to ANSI SQL, which considers EXISTS to be a | EXISTS '(' query ')' #exists | CASE valueExpression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CAST '(' expression AS dataType ')' #cast | TRY_CAST '(' expression AS dataType ')' #cast | ARRAY '[' (expression (',' expression)*)? ']' #arrayConstructor | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier[null] #columnReference | expr=primaryExpression '.' fieldName=identifier[null] #dereference | name=CURRENT_DATE #specialDateTimeFunction | name=CURRENT_TIME ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction | name=CURRENT_TIMESTAMP ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction | name=LOCALTIME ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction | name=LOCALTIMESTAMP ('(' precision=INTEGER_VALUE ')')? #specialDateTimeFunction | name=CURRENT_USER #currentUser | SUBSTRING '(' valueExpression FROM valueExpression (FOR valueExpression)? ')' #substring | NORMALIZE '(' valueExpression (',' normalForm)? ')' #normalize | EXTRACT '(' identifier[null] FROM valueExpression ')' #extract | '(' expression ')' #parenthesizedExpression | GROUPING '(' (qualifiedName (',' qualifiedName)*)? ')' #groupingOperation ; timeZoneSpecifier : TIME ZONE interval #timeZoneInterval | TIME ZONE string #timeZoneString ; interval : INTERVAL sign=(PLUS | MINUS)? string from=intervalField (TO to=intervalField)? ; orderBy : ORDER BY sortItem (',' sortItem)* ; string : STRING #basicStringLiteral | UNICODE_STRING (UESCAPE STRING)? #unicodeStringLiteral ; number : DECIMAL_VALUE #decimalLiteral | DOUBLE_VALUE #doubleLiteral | INTEGER_VALUE #integerLiteral ; nullTreatment : IGNORE NULLS | RESPECT NULLS ; comparisonOperator : EQ | NEQ | LT | LTE | GT | GTE ; comparisonQuantifier : ALL | SOME | ANY ; booleanValue : TRUE | FALSE ; intervalField : YEAR | MONTH | DAY | HOUR | MINUTE | SECOND ; normalForm : NFD | NFC | NFKD | NFKC ; //dataTypes // : '(' (dataType (',' dataType)*)? ')' // ; dataType : primitiveType | arrayType | mapType | structType | unionType ; primitiveType : TINYINT | SMALLINT | INT | BIGINT | BOOLEAN | FLOAT | DOUBLE | DOUBLE PRECISION | STRING | BINARY | TIMESTAMP | DECIMAL | DECIMAL '(' INTEGER_VALUE ',' INTEGER_VALUE ')' | DATE | VARCHAR | CHAR ; arrayType : ARRAY '<' dataType '>' ; mapType : MAP < primitiveType, dataType > ; structType : STRUCT '<' columnName=identifier[null] ':' dataType (COMMENT comment=string)? (',' columnName=identifier[null] ':' dataType (COMMENT comment=string)? )* '>' ; unionType : UNIONTYPE '<' dataType (',' dataType)* '>' ; parameterExpression returns [int index] : '?' { $index = NextBindParameterIndex(); } ; //type // : type ARRAY // | ARRAY '<' type '>' // | MAP '<' type ',' type '>' // | ROW '(' identifier[null] type (',' identifier[null] type)* ')' // | baseType ('(' typeParameter (',' typeParameter)* ')')? // | INTERVAL from=intervalField TO to=intervalField // ; //typeParameter // : INTEGER_VALUE | type // ; // //baseType // : TIME_WITH_TIME_ZONE // | TIMESTAMP_WITH_TIME_ZONE // | DOUBLE_PRECISION // | qualifiedName // ; whenClause : WHEN condition=expression THEN result=expression ; filter : FILTER '(' WHERE booleanExpression ')' ; over : OVER '(' windowSpecification ')' ; windowSpecification: partitionBy? orderBy? windowFrame? ; partitionBy: PARTITION BY partition+=expression (',' partition+=expression)* ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=PRECEDING #unboundedFrame | UNBOUNDED boundType=FOLLOWING #unboundedFrame | CURRENT ROW #currentRowBound | expression boundType=(PRECEDING | FOLLOWING) #boundedFrame // expression should be unsignedLiteral ; explainOption : FORMAT value=(TEXT | GRAPHVIZ | JSON) #explainFormat | TYPE value=(LOGICAL | DISTRIBUTED | VALIDATE | IO) #explainType ; //transactionMode // : ISOLATION LEVEL levelOfIsolation #isolationLevel // | READ accessMode=(ONLY | WRITE) #transactionAccessMode // ; //levelOfIsolation // : READ UNCOMMITTED #readUncommitted // | READ COMMITTED #readCommitted // | REPEATABLE READ #repeatableRead // | SERIALIZABLE #serializable // ; //callArgument // : expression #positionalArgument // | identifier[null] '=>' expression #namedArgument // ; //privilege // : SELECT | DELETE | INSERT | identifier[null] // ; qualifiedName returns [QsiQualifiedIdentifier qqi] locals [List buffer] @init { $buffer = new List(); } @after { $qqi = new QsiQualifiedIdentifier($buffer); } : identifier[$buffer] ('.' identifier[$buffer] )* ; //grantor // : CURRENT_USER #currentUserGrantor // | CURRENT_ROLE #currentRoleGrantor // | principal #specifiedPrincipal // ; //principal // : USER identifier[null] #userPrincipal // | ROLE identifier[null] #rolePrincipal // | identifier[null] #unspecifiedPrincipal // ; //roles // : identifier[null] (',' identifier[null])* // ; identifier[List buffer] returns [QsiIdentifier qi] @after { $buffer?.Add($qi); } : i=IDENTIFIER { $qi = new QsiIdentifier($i.text.ToUpper(), false); } #unquotedIdentifier | i=QUOTED_IDENTIFIER { $qi = new QsiIdentifier($i.text, true); } #quotedIdentifier | ki=nonReserved { $qi = new QsiIdentifier($ki.text.ToUpper(), false); } #unquotedIdentifier | i=BACKQUOTED_IDENTIFIER { $qi = new QsiIdentifier($i.text, true); } #backQuotedIdentifier | i=DIGIT_IDENTIFIER { $qi = new QsiIdentifier($i.text.ToUpper(), false); } #digitIdentifier ; nonReserved // IMPORTANT: this rule must only contain tokens. Nested rules are not supported. See SqlParser.exitNonReserved : ADD | AFTER | ADMIN | ALL | ANALYZE | ANY | ARRAY | ASC | AT | BERNOULLI | CALL | CALLED | CASCADE | CATALOGS | CHANGE | COLUMN | COLUMNS | COMMENT | COMMIT | COMMITTED | CURRENT | CURRENT_ROLE | DATA | DATE | DAY | DEFINER | DESC | DETERMINISTIC | DISTRIBUTED | EXCLUDING | EXPLAIN | EXTERNAL | FILTER | FIRST | FOLLOWING | FORMAT | FUNCTION | FUNCTIONS | GRANT | GRANTED | GRANTS | GRAPHVIZ | HOUR | IF | IGNORE | INCLUDING | INPUT | INTERVAL | INVOKER | IO | ISOLATION | JSON | LANGUAGE | LAST | LATERAL | LEVEL | LIMIT | LOGICAL | MAP | MATERIALIZED | MINUTE | MONTH | NAME | NFC | NFD | NFKC | NFKD | NO | NONE | NULLIF | NULLS | OFFSET | ONLY | OPTION | ORDINALITY | OUTPUT | OVER | PARTITION | PARTITIONS | POSITION | PRECEDING | PRIVILEGES | PROPERTIES | RANGE | READ | REFRESH | RENAME | REPEATABLE | REPLACE | RESET | RESPECT | RESTRICT | RETURN | RETURNS | REVOKE | ROLE | ROLES | ROLLBACK | ROW | ROWS | SCHEMA | SCHEMAS | SECOND | SECURITY | SERIALIZABLE | SESSION | SET | SETS | SQL | SHOW | SOME | START | STATS | SUBSTRING | SYSTEM | TABLES | TABLESAMPLE | TEMPORARY | TEXT | TIME | TIMESTAMP | TO | TRANSACTION | TRY_CAST | TYPE | UNBOUNDED | UNCOMMITTED | USE | USER | VALIDATE | VERBOSE | VIEW | WORK | WRITE | YEAR | ZONE | SYNC | PROTECTION | PURGE | SKEWED | DIRECTORIES | SORTED | REMOTE | MANAGEDLOCATION; ADD: 'ADD'; ADMIN: 'ADMIN'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANY: 'ANY'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; BERNOULLI: 'BERNOULLI'; BETWEEN: 'BETWEEN'; BY: 'BY'; CALL: 'CALL'; CALLED: 'CALLED'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CATALOGS: 'CATALOGS'; CHANGE: 'CHANGE'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMMITTED: 'COMMITTED'; CONSTRAINT: 'CONSTRAINT'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_ROLE: 'CURRENT_ROLE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATE: 'DATE'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEALLOCATE: 'DEALLOCATE'; DEFINER: 'DEFINER'; DELETE: 'DELETE'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DETERMINISTIC: 'DETERMINISTIC'; DISTINCT: 'DISTINCT'; DISTRIBUTED: 'DISTRIBUTED'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; EXCEPT: 'EXCEPT'; EXCLUDING: 'EXCLUDING'; EXECUTE: 'EXECUTE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXTRACT: 'EXTRACT'; EXTERNAL: 'EXTERNAL'; FALSE: 'FALSE'; FILTER: 'FILTER'; FIRST: 'FIRST'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FORMAT: 'FORMAT'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GRANT: 'GRANT'; GRANTED: 'GRANTED'; GRANTS: 'GRANTS'; GRAPHVIZ: 'GRAPHVIZ'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IN: 'IN'; INCLUDING: 'INCLUDING'; INNER: 'INNER'; INPUT: 'INPUT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; INVOKER: 'INVOKER'; IO: 'IO'; IS: 'IS'; ISOLATION: 'ISOLATION'; JSON: 'JSON'; JOIN: 'JOIN'; LANGUAGE: 'LANGUAGE'; LAST: 'LAST'; LATERAL: 'LATERAL'; LEFT: 'LEFT'; LEVEL: 'LEVEL'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LOCATION: 'LOCATION'; LOCALTIME: 'LOCALTIME'; LOCALTIMESTAMP: 'LOCALTIMESTAMP'; LOGICAL: 'LOGICAL'; MAP: 'MAP'; MATERIALIZED: 'MATERIALIZED'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; NAME: 'NAME'; NATURAL: 'NATURAL'; NFC : 'NFC'; NFD : 'NFD'; NFKC : 'NFKC'; NFKD : 'NFKD'; NO: 'NO'; NONE: 'NONE'; NORMALIZE: 'NORMALIZE'; NOT: 'NOT'; NULL: 'NULL'; NULLIF: 'NULLIF'; NULLS: 'NULLS'; OFFSET: 'OFFSET'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OR: 'OR'; ORDER: 'ORDER'; ORDINALITY: 'ORDINALITY'; OUTER: 'OUTER'; OUTPUT: 'OUTPUT'; OVER: 'OVER'; PARTITION: 'PARTITION'; PARTITIONS: 'PARTITIONS'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PREPARE: 'PREPARE'; PRIVILEGES: 'PRIVILEGES'; PROPERTIES: 'PROPERTIES'; RANGE: 'RANGE'; READ: 'READ'; RECURSIVE: 'RECURSIVE'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPEATABLE: 'REPEATABLE'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; RETURN: 'RETURN'; RETURNS: 'RETURNS'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SCHEMAS: 'SCHEMAS'; SECOND: 'SECOND'; SECURITY: 'SECURITY'; SELECT: 'SELECT'; SERIALIZABLE: 'SERIALIZABLE'; SESSION: 'SESSION'; SET: 'SET'; SETS: 'SETS'; SHOW: 'SHOW'; SOME: 'SOME'; SQL: 'SQL'; START: 'START'; STATS: 'STATS'; SUBSTRING: 'SUBSTRING'; SYSTEM: 'SYSTEM'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TEMPORARY: 'TEMPORARY'; TEXT: 'TEXT'; THEN: 'THEN'; TIME: 'TIME'; TIMESTAMP: 'TIMESTAMP'; TO: 'TO'; TRANSACTION: 'TRANSACTION'; TRUE: 'TRUE'; TRY_CAST: 'TRY_CAST'; TYPE: 'TYPE'; UESCAPE: 'UESCAPE'; UNBOUNDED: 'UNBOUNDED'; UNCOMMITTED: 'UNCOMMITTED'; UNION: 'UNION'; UNNEST: 'UNNEST'; UNLOAD: 'UNLOAD'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALIDATE: 'VALIDATE'; VALUES: 'VALUES'; VERBOSE: 'VERBOSE'; VIEW: 'VIEW'; WHEN: 'WHEN'; WHERE: 'WHERE'; WITH: 'WITH'; WORK: 'WORK'; WRITE: 'WRITE'; YEAR: 'YEAR'; ZONE: 'ZONE'; PARTITIONED: 'PARTITIONED'; CLUSTERED: 'CLUSTERED'; BUCKETS: 'BUCKETS'; STORED: 'STORED'; SERDEPROPERTIES: 'SERDEPROPERTIES'; TBLPROPERTIES: 'TBLPROPERTIES'; DELIMITED: 'DELIMITED'; FIELDS: 'FIELDS'; TERMINATED: 'TERMINATED'; ESCAPED: 'ESCAPED'; COLLECTION: 'COLLECTION'; ITEMS: 'ITEMS'; KEYS: 'KEYS'; LINES: 'LINES'; DEFINED: 'DEFINED'; SERDE: 'SERDE'; SEQUENCEFILE: 'SEQUENCEFILE'; TEXTFILE: 'TEXTFILE'; RCFILE: 'RCFILE'; ORC: 'ORC'; PARQUET: 'PARQUET'; AVRO: 'AVRO'; INPUTFORMAT: 'INPUTFORMAT'; OUTPUTFORMAT: 'OUTPUTFORMAT'; EXTENDED: 'EXTENDED'; FORMATTED: 'FORMATTED'; MSCK: 'MSCK'; REPAIR: 'REPAIR'; DATABASES: 'DATABASES'; VIEWS: 'VIEWS'; SYNC: 'SYNC'; PROTECTION: 'PROTECTION'; PURGE: 'PURGE'; SKEWED: 'SKEWED'; DIRECTORIES: 'DIRECTORIES'; SORTED: 'SORTED'; JSONFILE: 'JSONFILE'; REMOTE: 'REMOTE'; MANAGEDLOCATION: 'MANAGEDLOCATION'; TINYINT: 'TINYINT'; BIGINT: 'BIGINT'; INT: 'INT'; SMALLINT: 'SMALLINT'; BOOLEAN: 'BOOLEAN'; FLOAT: 'FLOAT'; DOUBLE: 'DOUBLE'; PRECISION: 'PRECISION'; BINARY: 'BINARY'; DECIMAL: 'DECIMAL'; VARCHAR: 'VARCHAR'; CHAR: 'CHAR'; STRUCT: 'STRUCT'; UNIONTYPE: 'UNIONTYPE'; EQ : '='; NEQ : '<>' | '!='; LT : '<'; LTE : '<='; GT : '>'; GTE : '>='; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; CONCAT: '||'; STRING : '\\'' ( ~'\\'' | '\\'\\'' )* '\\'' ; UNICODE_STRING : 'U&\\'' ( ~'\\'' | '\\'\\'' )* '\\'' ; // Note: we allow any character inside the binary literal and validate // its a correct literal when the AST is being constructed. This // allows us to provide more meaningful error messages to the user BINARY_LITERAL : 'X\\'' (~'\\'')* '\\'' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; DOUBLE_VALUE : DIGIT+ ('.' DIGIT*)? EXPONENT | '.' DIGIT+ EXPONENT ; IDENTIFIER : (LETTER | '_') (LETTER | DIGIT | '_' | '@' | ':')* ; DIGIT_IDENTIFIER : DIGIT (LETTER | DIGIT | '_' | '@' | ':')+ ; QUOTED_IDENTIFIER : '""' ( ~'""' | '""""' )* '""' ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; TIME_WITH_TIME_ZONE : 'TIME' WS 'WITH' WS 'TIME' WS 'ZONE' ; TIMESTAMP_WITH_TIME_ZONE : 'TIMESTAMP' WS 'WITH' WS 'TIME' WS 'ZONE' ; DOUBLE_PRECISION : 'DOUBLE' WS 'PRECISION' ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",16256,True,2771.414701104356,median "/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // HPL/SQL Procedural SQL Extension Grammar grammar Hplsql; program : block EOF; block : ((begin_end_block | stmt) T_GO?)+ ; // Multiple consecutive blocks/statements begin_end_block : declare_block? T_BEGIN block exception_block? block_end ; single_block_stmt : // Single BEGIN END block (but nested blocks are possible) or single statement T_BEGIN block exception_block? block_end | stmt T_SEMICOLON? ; block_end : {!_input.LT(2).getText().equalsIgnoreCase(""TRANSACTION"")}? T_END ; proc_block : begin_end_block | stmt+ T_GO? ; stmt : assignment_stmt | allocate_cursor_stmt | alter_table_stmt | associate_locator_stmt | begin_transaction_stmt | break_stmt | call_stmt | collect_stats_stmt | close_stmt | cmp_stmt | copy_from_local_stmt | copy_stmt | commit_stmt | create_database_stmt | create_function_stmt | create_index_stmt | create_local_temp_table_stmt | create_package_stmt | create_package_body_stmt | create_procedure_stmt | create_table_stmt | declare_stmt | delete_stmt | describe_stmt | drop_stmt | end_transaction_stmt | exec_stmt | exit_stmt | fetch_stmt | for_cursor_stmt | for_range_stmt | if_stmt | include_stmt | cte_insert_stmt | multiple_insert_stmt | insert_stmt | insert_directory_stmt | get_diag_stmt | grant_stmt | leave_stmt | map_object_stmt | merge_stmt | open_stmt | print_stmt | quit_stmt | raise_stmt | resignal_stmt | return_stmt | rollback_stmt | select_stmt | signal_stmt | summary_stmt | update_stmt | use_stmt | truncate_stmt | values_into_stmt | loop_stmt | while_stmt | label | hive | host | null_stmt | expr_stmt | semicolon_stmt // Placed here to allow null statements ;;... ; semicolon_stmt : T_SEMICOLON | '@' | '#' | '/' ; exception_block : // Exception block T_EXCEPTION exception_block_item+ ; exception_block_item : T_WHEN L_ID T_THEN block ~(T_WHEN | T_END) ; null_stmt : // NULL statement (no operation) T_NULL ; expr_stmt : // Standalone expression {!_input.LT(1).getText().equalsIgnoreCase(""GO"")}? expr ; assignment_stmt : // Assignment statement T_SET set_session_option | T_SET? assignment_stmt_item (T_COMMA assignment_stmt_item)* ; assignment_stmt_item : assignment_stmt_select_item | assignment_stmt_single_item | assignment_stmt_multiple_item ; assignment_stmt_single_item : ident T_COLON? T_EQUAL expr | T_OPEN_P ident T_CLOSE_P T_COLON? T_EQUAL expr ; assignment_stmt_multiple_item : T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P T_COLON? T_EQUAL T_OPEN_P expr (T_COMMA expr)* T_CLOSE_P ; assignment_stmt_select_item : (ident | (T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P)) T_COLON? T_EQUAL T_OPEN_P select_stmt T_CLOSE_P ; allocate_cursor_stmt: T_ALLOCATE ident T_CURSOR T_FOR ((T_RESULT T_SET) | T_PROCEDURE) ident ; associate_locator_stmt : T_ASSOCIATE (T_RESULT T_SET)? (T_LOCATOR | T_LOCATORS) T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P T_WITH T_PROCEDURE ident ; begin_transaction_stmt : T_BEGIN T_TRANSACTION ; break_stmt : T_BREAK ; call_stmt : T_CALL ident (T_OPEN_P expr_func_params? T_CLOSE_P | expr_func_params)? ; declare_stmt : // Declaration statement T_DECLARE declare_stmt_item (T_COMMA declare_stmt_item)* ; declare_block : // Declaration block T_DECLARE declare_stmt_item T_SEMICOLON (declare_stmt_item T_SEMICOLON)* ; declare_block_inplace : declare_stmt_item T_SEMICOLON (declare_stmt_item T_SEMICOLON)* ; declare_stmt_item : declare_cursor_item | declare_condition_item | declare_handler_item | declare_var_item | declare_temporary_table_item ; declare_var_item : ident (T_COMMA ident)* T_AS? dtype dtype_len? dtype_attr* dtype_default? | ident T_CONSTANT T_AS? dtype dtype_len? dtype_default ; declare_condition_item : // Condition declaration ident T_CONDITION ; declare_cursor_item : // Cursor declaration (T_CURSOR ident | ident T_CURSOR) (cursor_with_return | cursor_without_return)? (T_IS | T_AS | T_FOR) (select_stmt | expr ) ; cursor_with_return : T_WITH T_RETURN T_ONLY? (T_TO (T_CALLER | T_CLIENT))? ; cursor_without_return : T_WITHOUT T_RETURN ; declare_handler_item : // Condition handler declaration (T_CONTINUE | T_EXIT) T_HANDLER T_FOR declare_handler_for_condition (T_COMMA declare_handler_for_condition)* single_block_stmt ; declare_handler_for_condition : T_SQLEXCEPTION | T_SQLWARNING | T_NOT T_FOUND | T_SQLSTATE string | ident ; declare_temporary_table_item : // DECLARE TEMPORARY TABLE statement T_GLOBAL? T_TEMPORARY T_TABLE ident create_table_preoptions? create_table_definition ; create_table_stmt : T_CREATE T_TABLE (T_IF T_NOT T_EXISTS)? table_name create_table_preoptions? create_table_definition ; create_local_temp_table_stmt : T_CREATE (T_LOCAL T_TEMPORARY | (T_SET | T_MULTISET)? T_VOLATILE) T_TABLE ident create_table_preoptions? create_table_definition ; create_table_definition : (T_AS? T_OPEN_P select_stmt T_CLOSE_P | T_AS? select_stmt | T_OPEN_P create_table_columns T_CLOSE_P | T_LIKE table_name) create_table_options? ; create_table_columns : create_table_columns_item (T_COMMA create_table_columns_item)* ; create_table_columns_item : column_name dtype dtype_len? dtype_attr* create_table_column_inline_cons* | (T_CONSTRAINT ident)? create_table_column_cons ; column_name : ident ; create_table_column_inline_cons : dtype_default | T_NOT? T_NULL | T_PRIMARY T_KEY | T_UNIQUE | T_REFERENCES table_name T_OPEN_P ident T_CLOSE_P create_table_fk_action* | T_IDENTITY T_OPEN_P L_INT (T_COMMA L_INT)* T_CLOSE_P | T_AUTO_INCREMENT | T_ENABLE ; create_table_column_cons : T_PRIMARY T_KEY T_CLUSTERED? T_OPEN_P ident (T_ASC | T_DESC)? (T_COMMA ident (T_ASC | T_DESC)?)* T_CLOSE_P T_ENABLE? index_storage_clause? | T_FOREIGN T_KEY T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P T_REFERENCES table_name T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P create_table_fk_action* ; create_table_fk_action : T_ON (T_UPDATE | T_DELETE) (T_NO T_ACTION | T_RESTRICT | T_SET T_NULL | T_SET T_DEFAULT | T_CASCADE) ; create_table_preoptions : create_table_preoptions_item+ ; create_table_preoptions_item : T_COMMA create_table_preoptions_td_item | create_table_options_hive_item ; create_table_preoptions_td_item : T_NO? (T_LOG | T_FALLBACK) ; create_table_options : create_table_options_item+ ; create_table_options_item : T_ON T_COMMIT (T_DELETE | T_PRESERVE) T_ROWS | create_table_options_ora_item | create_table_options_db2_item | create_table_options_td_item | create_table_options_hive_item | create_table_options_mssql_item | create_table_options_mysql_item ; create_table_options_ora_item : T_SEGMENT T_CREATION (T_IMMEDIATE | T_DEFERRED) | (T_PCTFREE | T_PCTUSED | T_INITRANS | T_MAXTRANS) L_INT | T_NOCOMPRESS | (T_LOGGING | T_NOLOGGING) | T_STORAGE T_OPEN_P (ident | L_INT)+ T_CLOSE_P | T_TABLESPACE ident ; create_table_options_db2_item : T_INDEX? T_IN ident | T_WITH T_REPLACE | T_DISTRIBUTE T_BY T_HASH T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P | T_NOT? T_LOGGED | T_COMPRESS (T_YES | T_NO) | T_DEFINITION T_ONLY | T_WITH T_RESTRICT T_ON T_DROP ; create_table_options_td_item : T_UNIQUE? T_PRIMARY T_INDEX T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P | T_WITH T_DATA ; create_table_options_hive_item : create_table_hive_row_format | T_STORED T_AS ident | T_PARTITIONED T_BY create_routine_params | T_CLUSTERED T_BY T_OPEN_P ident T_CLOSE_P (T_SORTED T_BY T_OPEN_P ident T_CLOSE_P)? T_INTO L_INT T_BUCKETS | T_TBLPROPERTIES T_OPEN_P ident T_EQUAL expr (T_COMMA ident T_EQUAL expr)* T_CLOSE_P ; create_table_hive_row_format : T_ROW T_FORMAT T_DELIMITED create_table_hive_row_format_fields* ; create_table_hive_row_format_fields : T_FIELDS T_TERMINATED T_BY expr (T_ESCAPED T_BY expr)? | T_COLLECTION T_ITEMS T_TERMINATED T_BY expr | T_MAP T_KEYS T_TERMINATED T_BY expr | T_LINES T_TERMINATED T_BY expr | T_NULL T_DEFINED T_AS expr ; create_table_options_mssql_item : T_ON ident | T_TEXTIMAGE_ON ident ; create_table_options_mysql_item : T_AUTO_INCREMENT T_EQUAL? expr | T_COMMENT T_EQUAL? expr | T_DEFAULT? (T_CHARACTER T_SET | T_CHARSET) T_EQUAL? expr | T_ENGINE T_EQUAL? expr ; alter_table_stmt : T_ALTER T_TABLE table_name alter_table_item ; alter_table_item : alter_table_add_constraint ; alter_table_add_constraint : T_ADD2 (T_CONSTRAINT ident)? alter_table_add_constraint_item ; alter_table_add_constraint_item : T_PRIMARY T_KEY T_CLUSTERED? T_OPEN_P ident (T_ASC | T_DESC)? (T_COMMA ident (T_ASC | T_DESC)?)* T_CLOSE_P T_ENABLE? index_storage_clause? | T_FOREIGN T_KEY T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P T_REFERENCES table_name T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P create_table_fk_action* | T_DEFAULT expr T_FOR ident ; dtype : // Data types T_CHAR | T_CHARACTER | T_BIGINT | T_BINARY_DOUBLE | T_BINARY_FLOAT | T_BINARY_INTEGER | T_BIT | T_DATE | T_DATETIME | T_DEC | T_DECIMAL | T_DOUBLE T_PRECISION? | T_FLOAT | T_INT | T_INT2 | T_INT4 | T_INT8 | T_INTEGER | T_NCHAR | T_NVARCHAR | T_NUMBER | T_NUMERIC | T_PLS_INTEGER | T_REAL | T_RESULT_SET_LOCATOR T_VARYING | T_SIMPLE_FLOAT | T_SIMPLE_DOUBLE | T_SIMPLE_INTEGER | T_SMALLINT | T_SMALLDATETIME | T_STRING | T_SYS_REFCURSOR | T_TIMESTAMP | T_TINYINT | T_VARCHAR | T_VARCHAR2 | T_XML | ident ('%' (T_TYPE | T_ROWTYPE))? // User-defined or derived data type ; dtype_len : // Data type length or size specification T_OPEN_P (L_INT | T_MAX) (T_CHAR | T_BYTE)? (T_COMMA L_INT)? T_CLOSE_P ; dtype_attr : T_NOT? T_NULL | T_CHARACTER T_SET ident | T_NOT? (T_CASESPECIFIC | T_CS) ; dtype_default : T_COLON? T_EQUAL expr | T_WITH? T_DEFAULT expr? ; create_database_stmt : T_CREATE (T_DATABASE | T_SCHEMA) (T_IF T_NOT T_EXISTS)? expr create_database_option* ; create_database_option : T_COMMENT expr | T_LOCATION expr ; create_function_stmt : (T_ALTER | T_CREATE (T_OR T_REPLACE)? | T_REPLACE)? T_FUNCTION ident create_routine_params? create_function_return (T_AS | T_IS)? declare_block_inplace? single_block_stmt ; create_function_return : (T_RETURN | T_RETURNS) dtype dtype_len? ; create_package_stmt : (T_ALTER | T_CREATE (T_OR T_REPLACE)? | T_REPLACE)? T_PACKAGE ident (T_AS | T_IS) package_spec T_END (ident T_SEMICOLON)? ; package_spec : package_spec_item T_SEMICOLON (package_spec_item T_SEMICOLON)* ; package_spec_item : declare_stmt_item | T_FUNCTION ident create_routine_params? create_function_return | (T_PROCEDURE | T_PROC) ident create_routine_params? ; create_package_body_stmt : (T_ALTER | T_CREATE (T_OR T_REPLACE)? | T_REPLACE)? T_PACKAGE T_BODY ident (T_AS | T_IS) package_body T_END (ident T_SEMICOLON)? ; package_body : package_body_item T_SEMICOLON (package_body_item T_SEMICOLON)* ; package_body_item : declare_stmt_item | create_function_stmt | create_procedure_stmt ; create_procedure_stmt : (T_ALTER | T_CREATE (T_OR T_REPLACE)? | T_REPLACE)? (T_PROCEDURE | T_PROC) ident create_routine_params? create_routine_options? (T_AS | T_IS)? declare_block_inplace? label? proc_block (ident T_SEMICOLON)? ; create_routine_params : T_OPEN_P T_CLOSE_P | T_OPEN_P create_routine_param_item (T_COMMA create_routine_param_item)* T_CLOSE_P | {!_input.LT(1).getText().equalsIgnoreCase(""IS"") && !_input.LT(1).getText().equalsIgnoreCase(""AS"") && !(_input.LT(1).getText().equalsIgnoreCase(""DYNAMIC"") && _input.LT(2).getText().equalsIgnoreCase(""RESULT"")) }? create_routine_param_item (T_COMMA create_routine_param_item)* ; create_routine_param_item : (T_IN | T_OUT | T_INOUT | T_IN T_OUT)? ident dtype dtype_len? dtype_attr* dtype_default? | ident (T_IN | T_OUT | T_INOUT | T_IN T_OUT)? dtype dtype_len? dtype_attr* dtype_default? ; create_routine_options : create_routine_option+ ; create_routine_option : T_LANGUAGE T_SQL | T_SPECIFIC ident | (T_MODIFIES | T_CONTAINS | T_READS) T_SQL T_DATA? | T_NOT? T_DETERMINISTIC | T_CALLED T_ON T_NULL T_INPUT | T_AUTONOMOUS | T_COMMIT T_ON T_RETURN (T_YES | T_NO) | T_INHERIT T_SPECIAL T_REGISTERS | (T_OLD | T_NEW) T_SAVEPOINT T_LEVEL | T_NO? T_EXTERNAL T_ACTION | T_PARAMETER T_CCSID (T_ASCII | T_UNICODE) | T_SQL T_SECURITY (T_CREATOR | T_DEFINER | T_INVOKER | T_OWNER) | T_DYNAMIC? T_RESULT T_SETS L_INT ; drop_stmt : // DROP statement T_DROP T_TABLE (T_IF T_EXISTS)? table_name | T_DROP (T_DATABASE | T_SCHEMA) (T_IF T_EXISTS)? expr ; end_transaction_stmt : T_END T_TRANSACTION ; exec_stmt : // EXEC, EXECUTE IMMEDIATE statement (T_EXEC | T_EXECUTE) T_IMMEDIATE? expr (T_OPEN_P expr_func_params T_CLOSE_P | expr_func_params)? (T_INTO L_ID (T_COMMA L_ID)*)? using_clause? ; if_stmt : // IF statement if_plsql_stmt | if_tsql_stmt | if_bteq_stmt ; if_plsql_stmt : T_IF bool_expr T_THEN block elseif_block* else_block? T_END T_IF ; if_tsql_stmt : T_IF bool_expr single_block_stmt (T_ELSE single_block_stmt)? ; if_bteq_stmt : '.' T_IF bool_expr T_THEN single_block_stmt ; elseif_block : (T_ELSIF | T_ELSEIF) bool_expr T_THEN block ; else_block : T_ELSE block ; include_stmt : // INCLUDE statement T_INCLUDE (file_name | expr) ; cte_insert_stmt : cte_select_stmt (insert_stmt | multiple_insert_stmt) ; multiple_insert_stmt : from_clause insert_stmt+ ; insert_stmt : // INSERT statement T_INSERT (T_OVERWRITE T_TABLE | T_INTO T_TABLE?) table_name insert_stmt_cols? (select_stmt | insert_stmt_rows) ; insert_stmt_cols : T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P ; insert_stmt_rows : T_VALUES insert_stmt_row (T_COMMA insert_stmt_row)* ; insert_stmt_row: T_OPEN_P expr (T_COMMA expr)* T_CLOSE_P ; insert_directory_stmt : T_INSERT T_OVERWRITE T_LOCAL? T_DIRECTORY expr_file expr_select ; exit_stmt : T_EXIT L_ID? (T_WHEN bool_expr)? ; get_diag_stmt : // GET DIAGNOSTICS statement T_GET T_DIAGNOSTICS get_diag_stmt_item ; get_diag_stmt_item : get_diag_stmt_exception_item | get_diag_stmt_rowcount_item ; get_diag_stmt_exception_item : T_EXCEPTION L_INT ident T_EQUAL T_MESSAGE_TEXT ; get_diag_stmt_rowcount_item : ident T_EQUAL T_ROW_COUNT ; grant_stmt : T_GRANT grant_stmt_item (T_COMMA grant_stmt_item)* T_TO T_ROLE ident ; grant_stmt_item : T_EXECUTE T_ON T_PROCEDURE ident ; leave_stmt : T_LEAVE L_ID? ; map_object_stmt : T_MAP T_OBJECT expr (T_TO expr)? (T_AT expr)? ; open_stmt : // OPEN cursor statement T_OPEN L_ID (T_FOR (select_stmt | expr))? ; fetch_stmt : // FETCH cursor statement T_FETCH T_FROM? L_ID T_INTO L_ID (T_COMMA L_ID)* ; collect_stats_stmt : T_COLLECT (T_STATISTICS | T_STATS) T_ON table_name collect_stats_clause? ; collect_stats_clause : T_COLUMN T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P ; close_stmt : // CLOSE cursor statement T_CLOSE L_ID ; cmp_stmt : // CMP statement T_CMP (T_ROW_COUNT | T_SUM) cmp_source T_COMMA cmp_source ; cmp_source : (table_name where_clause? | T_OPEN_P select_stmt T_CLOSE_P) (T_AT ident)? ; copy_from_local_stmt : // COPY FROM LOCAL statement T_COPY T_FROM T_LOCAL copy_source (T_COMMA copy_source)* T_TO copy_target copy_file_option* ; copy_stmt : // COPY statement T_COPY (table_name | T_OPEN_P select_stmt T_CLOSE_P) T_TO T_HDFS? copy_target copy_option* ; copy_source : (file_name | expr) ; copy_target : (file_name | expr) ; copy_option : T_AT ident | T_BATCHSIZE expr | T_DELIMITER expr | T_SQLINSERT ident ; copy_file_option : T_DELETE | T_IGNORE | T_OVERWRITE ; commit_stmt : // COMMIT statement T_COMMIT T_WORK? ; create_index_stmt : // CREATE INDEX statement T_CREATE T_UNIQUE? T_INDEX ident T_ON table_name T_OPEN_P create_index_col (T_COMMA create_index_col)* T_CLOSE_P create_index_option* ; create_index_col : ident (T_ASC | T_DESC)? ; create_index_option : T_ALLOW T_REVERSE T_SCANS | T_COMPRESS T_YES ; index_storage_clause : index_mssql_storage_clause ; index_mssql_storage_clause : T_WITH T_OPEN_P ident T_EQUAL ident (T_COMMA ident T_EQUAL ident)* T_CLOSE_P create_table_options_mssql_item* ; print_stmt : // PRINT statement T_PRINT expr | T_PRINT T_OPEN_P expr T_CLOSE_P ; quit_stmt : '.'? T_QUIT expr? ; raise_stmt : T_RAISE ; resignal_stmt : // RESIGNAL statement T_RESIGNAL (T_SQLSTATE T_VALUE? expr (T_SET T_MESSAGE_TEXT T_EQUAL expr)? )? ; return_stmt : // RETURN statement T_RETURN expr? ; rollback_stmt : // ROLLBACK statement T_ROLLBACK T_WORK? ; set_session_option : set_current_schema_option | set_current_path_option | set_mssql_session_option | set_teradata_session_option ; set_current_schema_option : ((T_CURRENT? T_SCHEMA) | T_CURRENT_SCHEMA) T_EQUAL? expr ; set_current_path_option : T_CURRENT? T_PATH T_EQUAL expr (',' expr)* ; set_mssql_session_option : ( T_ANSI_NULLS | T_ANSI_PADDING | T_NOCOUNT | T_QUOTED_IDENTIFIER | T_XACT_ABORT ) (T_ON | T_OFF) ; set_teradata_session_option : T_QUERY_BAND T_EQUAL (expr | T_NONE) T_UPDATE? T_FOR (T_TRANSACTION | T_SESSION) ; signal_stmt : // SIGNAL statement T_SIGNAL ident string? ; summary_stmt : // SUMMARY statement T_SUMMARY (T_TOP expr)? T_FOR (select_stmt | table_name where_clause? (T_LIMIT expr)?) ; truncate_stmt : T_TRUNCATE T_TABLE? table_name ; use_stmt : // USE statement T_USE expr ; values_into_stmt : // VALUES INTO statement T_VALUES T_OPEN_P? expr (T_COMMA expr)* T_CLOSE_P? T_INTO T_OPEN_P? ident (T_COMMA ident)* T_CLOSE_P? ; loop_stmt : // WHILE loop statement T_LOOP block T_END T_LOOP ; while_stmt : // WHILE loop statement T_WHILE bool_expr (T_DO | T_LOOP | T_THEN | T_BEGIN) block T_END (T_WHILE | T_LOOP)? ; for_cursor_stmt : // FOR (cursor) statement T_FOR L_ID T_IN T_OPEN_P? select_stmt T_CLOSE_P? T_LOOP block T_END T_LOOP ; for_range_stmt : // FOR (Integer range) statement T_FOR L_ID T_IN T_REVERSE? expr T_DOT2 expr ((T_BY | T_STEP) expr)? T_LOOP block T_END T_LOOP ; label : L_LABEL | T_LESS T_LESS L_ID T_GREATER T_GREATER ; using_clause : // USING var,... clause T_USING expr (T_COMMA expr)* ; select_stmt : // SELECT statement cte_select_stmt? fullselect_stmt ; cte_select_stmt : T_WITH cte_select_stmt_item (T_COMMA cte_select_stmt_item)* ; cte_select_stmt_item : ident cte_select_cols? T_AS T_OPEN_P fullselect_stmt T_CLOSE_P ; cte_select_cols : T_OPEN_P ident (T_COMMA ident)* T_CLOSE_P ; fullselect_stmt : fullselect_stmt_item (fullselect_set_clause fullselect_stmt_item)* ; fullselect_stmt_item : subselect_stmt | T_OPEN_P fullselect_stmt T_CLOSE_P ; fullselect_set_clause : T_UNION T_ALL? | T_EXCEPT T_ALL? | T_INTERSECT T_ALL? ; subselect_stmt : (T_SELECT | T_SEL) select_list into_clause? from_clause? where_clause? group_by_clause? (having_clause | qualify_clause)? order_by_clause? select_options? ; select_list : select_list_set? select_list_limit? select_list_item (T_COMMA select_list_item)* ; select_list_set : T_ALL | T_DISTINCT ; select_list_limit : T_TOP expr ; select_list_item : ((ident T_EQUAL)? expr select_list_alias? | select_list_asterisk) ; select_list_alias : {!_input.LT(1).getText().equalsIgnoreCase(""INTO"") && !_input.LT(1).getText().equalsIgnoreCase(""FROM"")}? T_AS? ident | T_OPEN_P T_TITLE L_S_STRING T_CLOSE_P ; select_list_asterisk : (L_ID '.')? '*' ; into_clause : T_INTO ident (T_COMMA ident)* ; from_clause : T_FROM from_table_clause (from_join_clause)* ; from_table_clause : from_table_name_clause | from_subselect_clause | from_table_values_clause ; from_table_name_clause : table_name from_alias_clause? ; from_subselect_clause : T_OPEN_P select_stmt T_CLOSE_P from_alias_clause? ; from_join_clause : T_COMMA from_table_clause | from_join_type_clause from_table_clause T_ON bool_expr ; from_join_type_clause : T_INNER? T_JOIN | (T_LEFT | T_RIGHT | T_FULL) T_OUTER? T_JOIN ; from_table_values_clause: T_TABLE T_OPEN_P T_VALUES from_table_values_row (T_COMMA from_table_values_row)* T_CLOSE_P from_alias_clause? ; from_table_values_row: expr | T_OPEN_P expr (T_COMMA expr)* T_CLOSE_P ; from_alias_clause : {!_input.LT(1).getText().equalsIgnoreCase(""EXEC"") && !_input.LT(1).getText().equalsIgnoreCase(""EXECUTE"") && !_input.LT(1).getText().equalsIgnoreCase(""INNER"") && !_input.LT(1).getText().equalsIgnoreCase(""LEFT"") && !_input.LT(1).getText().equalsIgnoreCase(""GROUP"") && !_input.LT(1).getText().equalsIgnoreCase(""ORDER"") && !_input.LT(1).getText().equalsIgnoreCase(""LIMIT"") && !_input.LT(1).getText().equalsIgnoreCase(""WITH"")}? T_AS? ident (T_OPEN_P L_ID (T_COMMA L_ID)* T_CLOSE_P)? ; table_name : ident ; where_clause : T_WHERE bool_expr ; group_by_clause : T_GROUP T_BY expr (T_COMMA expr)* ; having_clause : T_HAVING bool_expr ; qualify_clause : T_QUALIFY bool_expr ; order_by_clause : T_ORDER T_BY expr (T_ASC | T_DESC)? (T_COMMA expr (T_ASC | T_DESC)?)* ; select_options : select_options_item+ ; select_options_item : T_LIMIT expr | T_FETCH T_FIRST expr (T_ROW | T_ROWS) T_ONLY | T_WITH (T_RR | T_RS | T_CS | T_UR) (T_USE T_AND T_KEEP (T_EXCLUSIVE | T_UPDATE | T_SHARE) T_LOCKS)? ; update_stmt : // UPDATE statement T_UPDATE update_table update_alias? T_SET update_assignment where_clause? update_upsert? ; update_alias : T_AS? ident ; update_assignment : assignment_stmt_item (T_COMMA assignment_stmt_item)* ; update_table : (table_name from_clause? | T_OPEN_P select_stmt T_CLOSE_P) ; update_upsert : T_ELSE insert_stmt ; merge_stmt : // MERGE statement T_MERGE T_INTO merge_table T_USING merge_table T_ON bool_expr merge_condition+ ; merge_table : (table_name | (T_OPEN_P select_stmt T_CLOSE_P)) (T_AS? ident)? ; merge_condition : T_WHEN T_NOT? T_MATCHED (T_AND bool_expr)? T_THEN merge_action | T_ELSE T_IGNORE ; merge_action : T_INSERT insert_stmt_cols? T_VALUES insert_stmt_row | T_UPDATE T_SET assignment_stmt_item (T_COMMA assignment_stmt_item)* where_clause? | T_DELETE ; delete_stmt : T_DELETE T_FROM? table_name delete_alias? (where_clause | T_ALL)? ; delete_alias : {!_input.LT(1).getText().equalsIgnoreCase(""ALL"")}? T_AS? ident ; describe_stmt : (T_DESCRIBE | T_DESC) T_TABLE? table_name ; bool_expr : // Boolean condition bool_expr_atom | bool_expr bool_expr_logical_operator bool_expr | T_NOT? T_OPEN_P bool_expr T_CLOSE_P ; bool_expr_atom : bool_expr_unary | bool_expr_binary | expr ; bool_expr_unary : expr T_IS T_NOT? T_NULL | expr T_BETWEEN expr T_AND expr | T_NOT? T_EXISTS T_OPEN_P select_stmt T_CLOSE_P | bool_expr_single_in | bool_expr_multi_in ; bool_expr_single_in : expr T_NOT? T_IN T_OPEN_P ((expr (T_COMMA expr)*) | select_stmt) T_CLOSE_P ; bool_expr_multi_in : T_OPEN_P expr (T_COMMA expr)* T_CLOSE_P T_NOT? T_IN T_OPEN_P select_stmt T_CLOSE_P ; bool_expr_binary : expr bool_expr_binary_operator expr ; bool_expr_logical_operator : T_AND | T_OR ; bool_expr_binary_operator : T_EQUAL | T_EQUAL2 | T_NOTEQUAL | T_NOTEQUAL2 | T_LESS | T_LESSEQUAL | T_GREATER | T_GREATEREQUAL | T_NOT? (T_LIKE | T_RLIKE | T_REGEXP) ; expr : expr interval_item | expr (T_MUL | T_DIV | T_MOD) expr | expr (T_ADD | T_SUB) expr | T_OPEN_P select_stmt T_CLOSE_P | T_OPEN_P expr T_CLOSE_P | expr_interval | expr_concat | expr_case | expr_cursor_attribute | expr_agg_window_func | expr_spec_func | expr_func | expr_atom ; expr_atom : date_literal | timestamp_literal | bool_literal | ident | string | dec_number | int_number | null_const ; expr_interval : T_INTERVAL expr interval_item ; interval_item : T_DAY | T_DAYS | T_MICROSECOND | T_MICROSECONDS | T_SECOND | T_SECONDS | T_MONTH | T_MONTHS | T_HOUR | T_HOURS | T_MINUTE | T_MINUTES | T_YEAR | T_YEARS ; expr_concat : // String concatenation operator expr_concat_item (T_PIPE | T_CONCAT) expr_concat_item ((T_PIPE | T_CONCAT) expr_concat_item)* ; expr_concat_item : T_OPEN_P expr T_CLOSE_P | expr_case | expr_agg_window_func | expr_spec_func | expr_func | expr_atom ; expr_case : // CASE expression expr_case_simple | expr_case_searched ; expr_case_simple : T_CASE expr (T_WHEN expr T_THEN stmt T_SEMICOLON?)+ (T_ELSE stmt T_SEMICOLON?)? T_END ; expr_case_searched : T_CASE (T_WHEN bool_expr T_THEN stmt T_SEMICOLON?)+ (T_ELSE stmt T_SEMICOLON?)? T_END ; expr_cursor_attribute : ident '%' (T_ISOPEN | T_FOUND | T_NOTFOUND) ; expr_agg_window_func : T_AVG T_OPEN_P expr_func_all_distinct? expr T_CLOSE_P expr_func_over_clause? | T_COUNT T_OPEN_P ((expr_func_all_distinct? expr) | '*') T_CLOSE_P expr_func_over_clause? | T_COUNT_BIG T_OPEN_P ((expr_func_all_distinct? expr) | '*') T_CLOSE_P expr_func_over_clause? | T_CUME_DIST T_OPEN_P T_CLOSE_P expr_func_over_clause | T_DENSE_RANK T_OPEN_P T_CLOSE_P expr_func_over_clause | T_FIRST_VALUE T_OPEN_P expr T_CLOSE_P expr_func_over_clause | T_LAG T_OPEN_P expr (T_COMMA expr (T_COMMA expr)?)? T_CLOSE_P expr_func_over_clause | T_LAST_VALUE T_OPEN_P expr T_CLOSE_P expr_func_over_clause | T_LEAD T_OPEN_P expr (T_COMMA expr (T_COMMA expr)?)? T_CLOSE_P expr_func_over_clause | T_MAX T_OPEN_P expr_func_all_distinct? expr T_CLOSE_P expr_func_over_clause? | T_MIN T_OPEN_P expr_func_all_distinct? expr T_CLOSE_P expr_func_over_clause? | T_RANK T_OPEN_P T_CLOSE_P expr_func_over_clause | T_ROW_NUMBER T_OPEN_P T_CLOSE_P expr_func_over_clause | T_STDEV T_OPEN_P expr_func_all_distinct? expr T_CLOSE_P expr_func_over_clause? | T_SUM T_OPEN_P expr_func_all_distinct? expr T_CLOSE_P expr_func_over_clause? | T_VAR T_OPEN_P expr_func_all_distinct? expr T_CLOSE_P expr_func_over_clause? | T_VARIANCE T_OPEN_P expr_func_all_distinct? expr T_CLOSE_P expr_func_over_clause? | T_LISTAGG T_OPEN_P expr T_COMMA expr T_CLOSE_P expr_func_within_clause? ; expr_func_all_distinct : T_ALL | T_DISTINCT ; expr_func_over_clause : T_OVER T_OPEN_P expr_func_partition_by_clause? order_by_clause? T_CLOSE_P ; expr_func_partition_by_clause : T_PARTITION T_BY expr (T_COMMA expr)* ; expr_func_within_clause : T_WITHIN T_GROUP T_OPEN_P order_by_clause T_CLOSE_P ; expr_spec_func : T_ACTIVITY_COUNT | T_CAST T_OPEN_P expr T_AS dtype dtype_len? T_CLOSE_P | T_COUNT T_OPEN_P (expr | '*') T_CLOSE_P | T_CURRENT_DATE | T_CURRENT T_DATE | (T_CURRENT_TIMESTAMP | T_CURRENT T_TIMESTAMP) (T_OPEN_P expr T_CLOSE_P)? | T_CURRENT_USER | T_CURRENT T_USER | T_MAX_PART_STRING T_OPEN_P expr (T_COMMA expr (T_COMMA expr T_EQUAL expr)*)? T_CLOSE_P | T_MIN_PART_STRING T_OPEN_P expr (T_COMMA expr (T_COMMA expr T_EQUAL expr)*)? T_CLOSE_P | T_MAX_PART_INT T_OPEN_P expr (T_COMMA expr (T_COMMA expr T_EQUAL expr)*)? T_CLOSE_P | T_MIN_PART_INT T_OPEN_P expr (T_COMMA expr (T_COMMA expr T_EQUAL expr)*)? T_CLOSE_P | T_MAX_PART_DATE T_OPEN_P expr (T_COMMA expr (T_COMMA expr T_EQUAL expr)*)? T_CLOSE_P | T_MIN_PART_DATE T_OPEN_P expr (T_COMMA expr (T_COMMA expr T_EQUAL expr)*)? T_CLOSE_P | T_PART_COUNT T_OPEN_P expr (T_COMMA expr T_EQUAL expr)* T_CLOSE_P | T_PART_LOC T_OPEN_P expr (T_COMMA expr T_EQUAL expr)+ (T_COMMA expr)? T_CLOSE_P | T_SUBSTRING T_OPEN_P expr T_FROM expr (T_FOR expr)? T_CLOSE_P | T_SYSDATE | T_USER ; expr_func : ident T_OPEN_P expr_func_params? T_CLOSE_P ; expr_func_params : func_param (T_COMMA func_param)* ; func_param : {!_input.LT(1).getText().equalsIgnoreCase(""INTO"")}? (ident T_EQUAL T_GREATER?)? expr ; expr_select : select_stmt | expr ; expr_file : file_name | expr ; hive : T_HIVE hive_item* ; hive_item : T_SUB ident expr | T_SUB ident L_ID T_EQUAL expr | T_SUB ident ; host : '!' host_cmd ';' // OS command | host_stmt ; host_cmd : .*? ; host_stmt : T_HOST expr ; file_name : L_FILE | ('/' | '.' '/')? ident ('/' ident)* ; date_literal : // DATE 'YYYY-MM-DD' literal T_DATE string ; timestamp_literal : // TIMESTAMP 'YYYY-MM-DD HH:MI:SS.FFF' literal T_TIMESTAMP string ; ident : '-'? (L_ID | non_reserved_words) ('.' (L_ID | non_reserved_words))* ; string : // String literal (single or double quoted) L_S_STRING # single_quotedString | L_D_STRING # double_quotedString ; int_number : // Integer (positive or negative) ('-' | '+')? L_INT ; dec_number : // Decimal number (positive or negative) ('-' | '+')? L_DEC ; bool_literal : // Boolean literal T_TRUE | T_FALSE ; null_const : // NULL constant T_NULL ; non_reserved_words : // Tokens that are not reserved words and can be used as identifiers T_ACTION | T_ACTIVITY_COUNT | T_ADD2 | T_ALL | T_ALLOCATE | T_ALTER | T_AND | T_ANSI_NULLS | T_ANSI_PADDING | T_AS | T_ASC | T_ASSOCIATE | T_AT | T_AUTO_INCREMENT | T_AVG | T_BATCHSIZE | T_BEGIN | T_BETWEEN | T_BIGINT | T_BINARY_DOUBLE | T_BINARY_FLOAT | T_BIT | T_BODY | T_BREAK | T_BY | T_BYTE | T_CALL | T_CALLER | T_CASCADE | T_CASE | T_CASESPECIFIC | T_CAST | T_CHAR | T_CHARACTER | T_CHARSET | T_CLIENT | T_CLOSE | T_CLUSTERED | T_CMP | T_COLLECT | T_COLLECTION | T_COLUMN | T_COMMENT | T_COMPRESS | T_CONSTANT | T_COPY | T_COMMIT | T_CONCAT | T_CONDITION | T_CONSTRAINT | T_CONTINUE | T_COUNT | T_COUNT_BIG | T_CREATE | T_CREATION | T_CREATOR | T_CS | T_CUME_DIST | T_CURRENT | T_CURRENT_DATE | T_CURRENT_SCHEMA | T_CURRENT_TIMESTAMP | T_CURRENT_USER | T_CURSOR | T_DATA | T_DATABASE | T_DATE | T_DATETIME | T_DAY | T_DAYS | T_DEC | T_DECIMAL | T_DECLARE | T_DEFAULT | T_DEFERRED | T_DEFINED | T_DEFINER | T_DEFINITION | T_DELETE | T_DELIMITED | T_DELIMITER | T_DENSE_RANK | T_DESC | T_DESCRIBE | T_DIAGNOSTICS | T_DIR | T_DIRECTORY | T_DISTINCT | T_DISTRIBUTE | T_DO | T_DOUBLE | T_DROP | T_DYNAMIC // T_ELSE reserved word // T_ELSEIF reserved word // T_ELSIF reserved word // T_END reserved word | T_ENABLE | T_ENGINE | T_ESCAPED | T_EXCEPT | T_EXEC | T_EXECUTE | T_EXCEPTION | T_EXCLUSIVE | T_EXISTS | T_EXIT | T_FALLBACK | T_FALSE | T_FETCH | T_FIELDS | T_FILE | T_FILES | T_FIRST_VALUE | T_FLOAT | T_FOR | T_FOREIGN | T_FORMAT | T_FOUND | T_FROM | T_FULL | T_FUNCTION | T_GET // | T_GLOBAL reserved word | T_GO | T_GRANT | T_GROUP | T_HANDLER | T_HASH | T_HAVING | T_HDFS | T_HIVE | T_HOST | T_IDENTITY | T_IF | T_IGNORE | T_IMMEDIATE | T_IN | T_INCLUDE | T_INDEX | T_INITRANS | T_INNER | T_INOUT | T_INSERT | T_INT | T_INT2 | T_INT4 | T_INT8 | T_INTEGER | T_INTERSECT | T_INTERVAL | T_INTO | T_INVOKER | T_ITEMS | T_IS | T_ISOPEN | T_JOIN | T_KEEP | T_KEY | T_KEYS | T_LAG | T_LANGUAGE | T_LAST_VALUE | T_LEAD | T_LEAVE | T_LEFT | T_LIKE | T_LIMIT | T_LINES | T_LISTAGG | T_LOCAL | T_LOCATION | T_LOCATOR | T_LOCATORS | T_LOCKS | T_LOG | T_LOGGED | T_LOGGING | T_LOOP | T_MAP | T_MATCHED | T_MAX | T_MAXTRANS | T_MERGE | T_MESSAGE_TEXT | T_MICROSECOND | T_MICROSECONDS | T_MIN | T_MONTH | T_MONTHS | T_MULTISET | T_NCHAR | T_NEW | T_NVARCHAR | T_NO | T_NOCOMPRESS | T_NOCOUNT | T_NOLOGGING | T_NONE | T_NOT | T_NOTFOUND // T_NULL reserved word | T_NUMERIC | T_NUMBER | T_OBJECT | T_OFF | T_ON | T_ONLY | T_OPEN | T_OR | T_ORDER | T_OUT | T_OUTER | T_OVER | T_OVERWRITE | T_OWNER | T_PACKAGE | T_PART_COUNT | T_PART_LOC | T_PARTITION | T_PCTFREE | T_PCTUSED | T_PRECISION | T_PRESERVE | T_PRIMARY | T_PRINT | T_PROC | T_PROCEDURE | T_PWD | T_QUALIFY | T_QUERY_BAND | T_QUIT | T_QUOTED_IDENTIFIER | T_RAISE | T_RANK | T_REAL | T_REFERENCES | T_REGEXP | T_RR | T_REPLACE | T_RESIGNAL | T_RESTRICT | T_RESULT | T_RESULT_SET_LOCATOR | T_RETURN | T_RETURNS | T_REVERSE | T_RIGHT | T_RLIKE | T_RS | T_ROLE | T_ROLLBACK | T_ROW | T_ROWS | T_ROW_COUNT | T_ROW_NUMBER | T_SCHEMA | T_SECOND | T_SECONDS | T_SECURITY | T_SEGMENT | T_SEL | T_SELECT | T_SESSION | T_SESSIONS | T_SET | T_SETS | T_SHARE | T_SIGNAL | T_SIMPLE_DOUBLE | T_SIMPLE_FLOAT | T_SMALLDATETIME | T_SMALLINT | T_SQL | T_SQLEXCEPTION | T_SQLINSERT | T_SQLSTATE | T_SQLWARNING | T_STATS | T_STATISTICS | T_STEP | T_STDEV | T_STORAGE | T_STORED | T_STRING | T_SUBDIR | T_SUBSTRING | T_SUM | T_SUMMARY | T_SYSDATE | T_SYS_REFCURSOR | T_TABLE | T_TABLESPACE | T_TEMPORARY | T_TERMINATED | T_TEXTIMAGE_ON | T_THEN | T_TIMESTAMP | T_TITLE | T_TO | T_TOP | T_TRANSACTION | T_TRIM | T_TRUE | T_TRUNCATE | T_TYPE // T_UNION reserved word | T_UNIQUE | T_UPDATE | T_UR | T_USE | T_USER | T_USING | T_VALUE | T_VALUES | T_VAR | T_VARCHAR | T_VARCHAR2 | T_VARYING | T_VARIANCE | T_VOLATILE // T_WHEN reserved word // T_WHERE reserved word | T_WHILE | T_WITH | T_WITHOUT | T_WORK | T_XACT_ABORT | T_XML | T_YEAR | T_YEARS | T_YES ; // Lexer rules T_ACTION : A C T I O N ; T_ADD2 : A D D ; T_ALL : A L L ; T_ALLOCATE : A L L O C A T E ; T_ALLOW : A L L O W ; T_ALTER : A L T E R ; T_AND : A N D ; T_ANSI_NULLS : A N S I '_' N U L L S ; T_ANSI_PADDING : A N S I '_' P A D D I N G ; T_AS : A S ; T_ASC : A S C ; T_ASCII : A S C I I ; T_ASSOCIATE : A S S O C I A T E ; T_AT : A T ; T_AUTO_INCREMENT : A U T O '_' I N C R E M E N T ; T_AUTONOMOUS : A U T O N O M O U S ; T_AVG : A V G ; T_BATCHSIZE : B A T C H S I Z E ; T_BEGIN : B E G I N ; T_BETWEEN : B E T W E E N ; T_BIGINT : B I G I N T ; T_BINARY_DOUBLE : B I N A R Y '_' D O U B L E ; T_BINARY_FLOAT : B I N A R Y '_' F L O A T ; T_BINARY_INTEGER : B I N A R Y '_' I N T E G E R ; T_BIT : B I T ; T_BODY : B O D Y ; T_BREAK : B R E A K ; T_BUCKETS : B U C K E T S ; T_BY : B Y ; T_BYTE : B Y T E ; T_CALL : C A L L ; T_CALLED : C A L L E D ; T_CALLER : C A L L E R ; T_CASCADE : C A S C A D E ; T_CASE : C A S E ; T_CASESPECIFIC : C A S E S P E C I F I C ; T_CAST : C A S T ; T_CCSID : C C S I D ; T_CHAR : C H A R ; T_CHARACTER : C H A R A C T E R ; T_CHARSET : C H A R S E T ; T_CLIENT : C L I E N T ; T_CLOSE : C L O S E ; T_CLUSTERED : C L U S T E R E D; T_CMP : C M P ; T_COLLECT : C O L L E C T ; T_COLLECTION : C O L L E C T I O N ; T_COLUMN : C O L U M N ; T_COMMENT : C O M M E N T; T_CONSTANT : C O N S T A N T ; T_CONTAINS : C O N T A I N S ; T_COMMIT : C O M M I T ; T_COMPRESS : C O M P R E S S ; T_CONCAT : C O N C A T; T_CONDITION : C O N D I T I O N ; T_CONSTRAINT : C O N S T R A I N T ; T_CONTINUE : C O N T I N U E ; T_COPY : C O P Y ; T_COUNT : C O U N T ; T_COUNT_BIG : C O U N T '_' B I G; T_CREATE : C R E A T E ; T_CREATION : C R E A T I O N ; T_CREATOR : C R E A T O R ; T_CS : C S; T_CURRENT : C U R R E N T ; T_CURRENT_SCHEMA : C U R R E N T '_' S C H E M A ; T_CURSOR : C U R S O R ; T_DATABASE : D A T A B A S E ; T_DATA : D A T A ; T_DATE : D A T E ; T_DATETIME : D A T E T I M E ; T_DAY : D A Y ; T_DAYS : D A Y S ; T_DEC : D E C ; T_DECIMAL : D E C I M A L ; T_DECLARE : D E C L A R E ; T_DEFAULT : D E F A U L T ; T_DEFERRED : D E F E R R E D ; T_DEFINED : D E F I N E D ; T_DEFINER : D E F I N E R ; T_DEFINITION : D E F I N I T I O N ; T_DELETE : D E L E T E ; T_DELIMITED : D E L I M I T E D ; T_DELIMITER : D E L I M I T E R ; T_DESC : D E S C ; T_DESCRIBE : D E S C R I B E ; T_DETERMINISTIC : D E T E R M I N I S T I C ; T_DIAGNOSTICS : D I A G N O S T I C S ; T_DIR : D I R ; T_DIRECTORY : D I R E C T O R Y ; T_DISTINCT : D I S T I N C T ; T_DISTRIBUTE : D I S T R I B U T E ; T_DO : D O ; T_DOUBLE : D O U B L E ; T_DROP : D R O P ; T_DYNAMIC : D Y N A M I C ; T_ELSE : E L S E ; T_ELSEIF : E L S E I F ; T_ELSIF : E L S I F ; T_ENABLE : E N A B L E ; T_END : E N D ; T_ENGINE : E N G I N E ; T_ESCAPED : E S C A P E D ; T_EXCEPT : E X C E P T ; T_EXEC : E X E C ; T_EXECUTE : E X E C U T E ; T_EXCEPTION : E X C E P T I O N ; T_EXCLUSIVE : E X C L U S I V E ; T_EXTERNAL : E X T E R N A L; T_EXISTS : E X I S T S ; T_EXIT : E X I T ; T_FALLBACK : F A L L B A C K ; T_FALSE : F A L S E ; T_FETCH : F E T C H ; T_FIELDS : F I E L D S ; T_FILE : F I L E ; T_FILES : F I L E S ; T_FLOAT : F L O A T ; T_FOR : F O R ; T_FOREIGN : F O R E I G N ; T_FORMAT : F O R M A T ; T_FOUND : F O U N D ; T_FROM : F R O M ; T_FULL : F U L L ; T_FUNCTION : F U N C T I O N ; T_GET : G E T ; T_GLOBAL : G L O B A L ; T_GO : G O ; T_GRANT : G R A N T ; T_GROUP : G R O U P ; T_HANDLER : H A N D L E R ; T_HASH : H A S H ; T_HAVING : H A V I N G ; T_HDFS : H D F S ; T_HIVE : H I V E ; T_HOST : H O S T ; T_HOUR : H O U R ; T_HOURS : H O U R S ; T_IDENTITY : I D E N T I T Y ; T_IF : I F ; T_IGNORE : I G N O R E ; T_IMMEDIATE : I M M E D I A T E ; T_IN : I N ; T_INCLUDE : I N C L U D E ; T_INDEX : I N D E X ; T_INHERIT : I N H E R I T ; T_INITRANS : I N I T R A N S ; T_INNER : I N N E R ; T_INOUT : I N O U T; T_INPUT : I N P U T ; T_INSERT : I N S E R T ; T_INT : I N T ; T_INT2 : I N T '2'; T_INT4 : I N T '4'; T_INT8 : I N T '8'; T_INTEGER : I N T E G E R ; T_INTERSECT : I N T E R S E C T ; T_INTERVAL : I N T E R V A L ; T_INTO : I N T O ; T_INVOKER : I N V O K E R ; T_IS : I S ; T_ISOPEN : I S O P E N ; T_ITEMS : I T E M S ; T_JOIN : J O I N ; T_KEEP : K E E P; T_KEY : K E Y ; T_KEYS : K E Y S ; T_LANGUAGE : L A N G U A G E ; T_LEAVE : L E A V E ; T_LEFT : L E F T ; T_LEVEL : L E V E L ; T_LIKE : L I K E ; T_LIMIT : L I M I T ; T_LINES : L I N E S ; T_LISTAGG : L I S T A G G ; T_LOCAL : L O C A L ; T_LOCATION : L O C A T I O N ; T_LOCATOR : L O C A T O R ; T_LOCATORS : L O C A T O R S ; T_LOCKS : L O C K S ; T_LOG : L O G ; T_LOGGED : L O G G E D ; T_LOGGING : L O G G I N G ; T_LOOP : L O O P ; T_MAP : M A P ; T_MATCHED : M A T C H E D ; T_MAX : M A X ; T_MAXTRANS : M A X T R A N S ; T_MERGE : M E R G E ; T_MESSAGE_TEXT : M E S S A G E '_' T E X T ; T_MICROSECOND : M I C R O S E C O N D ; T_MICROSECONDS : M I C R O S E C O N D S; T_MIN : M I N ; T_MINUTE : M I N U T E ; T_MINUTES : M I N U T E S ; T_MODIFIES : M O D I F I E S ; T_MONTH : M O N T H ; T_MONTHS : M O N T H S ; T_MULTISET : M U L T I S E T ; T_NCHAR : N C H A R ; T_NEW : N E W ; T_NVARCHAR : N V A R C H A R ; T_NO : N O ; T_NOCOUNT : N O C O U N T ; T_NOCOMPRESS : N O C O M P R E S S ; T_NOLOGGING : N O L O G G I N G ; T_NONE : N O N E ; T_NOT : N O T ; T_NOTFOUND : N O T F O U N D ; T_NULL : N U L L ; T_NUMERIC : N U M E R I C ; T_NUMBER : N U M B E R ; T_OBJECT : O B J E C T ; T_OFF : O F F ; T_OLD : O L D ; T_ON : O N ; T_ONLY : O N L Y ; T_OPEN : O P E N ; T_OR : O R ; T_ORDER : O R D E R; T_OUT : O U T ; T_OUTER : O U T E R ; T_OVER : O V E R ; T_OVERWRITE : O V E R W R I T E ; T_OWNER : O W N E R ; T_PARAMETER : P A R A M E T E R ; T_PACKAGE : P A C K A G E ; T_PARTITION : P A R T I T I O N ; T_PARTITIONED : P A R T I T I O N E D; T_PATH : P A T H ; T_PCTFREE : P C T F R E E ; T_PCTUSED : P C T U S E D ; T_PLS_INTEGER : P L S '_' I N T E G E R ; T_PRECISION : P R E C I S I O N ; T_PRESERVE : P R E S E R V E ; T_PRIMARY : P R I M A R Y ; T_PRINT : P R I N T ; T_PROC : P R O C ; T_PROCEDURE : P R O C E D U R E ; T_QUALIFY : Q U A L I F Y ; T_QUERY_BAND : Q U E R Y '_' B A N D ; T_QUIT : Q U I T ; T_QUOTED_IDENTIFIER : Q U O T E D '_' I D E N T I F I E R ; T_RAISE : R A I S E ; T_READS : R E A D S ; T_REAL : R E A L ; T_REFERENCES : R E F E R E N C E S ; T_REGISTERS : R E G I S T E R S ; T_REGEXP : R E G E X P ; T_REPLACE : R E P L A C E ; T_RESIGNAL : R E S I G N A L ; T_RESTRICT : R E S T R I C T ; T_RESULT : R E S U L T ; T_RESULT_SET_LOCATOR : R E S U L T '_' S E T '_' L O C A T O R ; T_RETURN : R E T U R N ; T_RETURNS : R E T U R N S ; T_REVERSE : R E V E R S E ; T_RIGHT : R I G H T ; T_RLIKE : R L I K E ; T_ROLE : R O L E ; T_ROLLBACK : R O L L B A C K ; T_ROW : R O W ; T_ROWS : R O W S ; T_ROWTYPE : R O W T Y P E ; T_ROW_COUNT : R O W '_' C O U N T ; T_RR : R R; T_RS : R S ; T_PWD : P W D ; T_TRIM : T R I M ; T_SAVEPOINT : S A V E P O I N T ; T_SCANS : S C A N S ; T_SCHEMA : S C H E M A ; T_SECOND : S E C O N D ; T_SECONDS : S E C O N D S; T_SECURITY : S E C U R I T Y ; T_SEGMENT : S E G M E N T ; T_SEL : S E L ; T_SELECT : S E L E C T ; T_SET : S E T ; T_SESSION : S E S S I O N ; T_SESSIONS : S E S S I O N S ; T_SETS : S E T S; T_SHARE : S H A R E ; T_SIGNAL : S I G N A L ; T_SIMPLE_DOUBLE : S I M P L E '_' D O U B L E ; T_SIMPLE_FLOAT : S I M P L E '_' F L O A T ; T_SIMPLE_INTEGER : S I M P L E '_' I N T E G E R ; T_SMALLDATETIME : S M A L L D A T E T I M E ; T_SMALLINT : S M A L L I N T ; T_SORTED : S O R T E D ; T_SPECIFIC : S P E C I F I C ; T_SPECIAL : S P E C I A L ; T_SQL : S Q L ; T_SQLEXCEPTION : S Q L E X C E P T I O N ; T_SQLINSERT : S Q L I N S E R T ; T_SQLSTATE : S Q L S T A T E ; T_SQLWARNING : S Q L W A R N I N G ; T_STATS : S T A T S ; T_STATISTICS : S T A T I S T I C S ; T_STEP : S T E P ; T_STORAGE : S T O R A G E ; T_STORED : S T O R E D ; T_STRING : S T R I N G ; T_SUBDIR : S U B D I R ; T_SUBSTRING : S U B S T R I N G ; T_SUM : S U M ; T_SUMMARY : S U M M A R Y ; T_SYS_REFCURSOR : S Y S '_' R E F C U R S O R ; T_TABLE : T A B L E ; T_TABLESPACE : T A B L E S P A C E ; T_TBLPROPERTIES : T B L P R O P E R T I E S ; T_TEMPORARY : T E M P O R A R Y ; T_TERMINATED : T E R M I N A T E D ; T_TEXTIMAGE_ON : T E X T I M A G E '_' O N ; T_THEN : T H E N ; T_TIMESTAMP : T I M E S T A M P ; T_TINYINT : T I N Y I N T ; T_TITLE : T I T L E ; T_TO : T O ; T_TOP : T O P ; T_TRANSACTION : T R A N S A C T I O N ; T_TRUE : T R U E ; T_TRUNCATE : T R U N C A T E; T_TYPE : T Y P E ; T_UNICODE : U N I C O D E ; T_UNION : U N I O N ; T_UNIQUE : U N I Q U E ; T_UPDATE : U P D A T E ; T_UR : U R ; T_USE : U S E ; T_USING : U S I N G ; T_VALUE : V A L U E ; T_VALUES : V A L U E S ; T_VAR : V A R ; T_VARCHAR : V A R C H A R ; T_VARCHAR2 : V A R C H A R '2' ; T_VARYING : V A R Y I N G ; T_VOLATILE : V O L A T I L E ; T_WHEN : W H E N ; T_WHERE : W H E R E ; T_WHILE : W H I L E ; T_WITH : W I T H ; T_WITHIN : W I T H I N; T_WITHOUT : W I T H O U T ; T_WORK : W O R K ; T_XACT_ABORT : X A C T '_' A B O R T ; T_XML : X M L ; T_YEAR : Y E A R ; T_YEARS : Y E A R S ; T_YES : Y E S ; // Functions with specific syntax T_ACTIVITY_COUNT : A C T I V I T Y '_' C O U N T ; T_CUME_DIST : C U M E '_' D I S T ; T_CURRENT_DATE : C U R R E N T '_' D A T E ; T_CURRENT_TIMESTAMP : C U R R E N T '_' T I M E S T A M P ; T_CURRENT_USER : C U R R E N T '_' U S E R ; T_DENSE_RANK : D E N S E '_' R A N K ; T_FIRST : F I R S T; T_FIRST_VALUE : F I R S T '_' V A L U E; T_LAG : L A G ; T_LAST_VALUE : L A S T '_' V A L U E; T_LEAD : L E A D ; T_MAX_PART_STRING : M A X '_' P A R T '_' S T R I N G ; T_MIN_PART_STRING : M I N '_' P A R T '_' S T R I N G ; T_MAX_PART_INT : M A X '_' P A R T '_' I N T ; T_MIN_PART_INT : M I N '_' P A R T '_' I N T ; T_MAX_PART_DATE : M A X '_' P A R T '_' D A T E ; T_MIN_PART_DATE : M I N '_' P A R T '_' D A T E ; T_PART_COUNT : P A R T '_' C O U N T ; T_PART_LOC : P A R T '_' L O C ; T_RANK : R A N K ; T_ROW_NUMBER : R O W '_' N U M B E R; T_STDEV : S T D E V ; T_SYSDATE : S Y S D A T E ; T_VARIANCE : V A R I A N C E ; T_USER : U S E R; T_ADD : '+' ; T_COLON : ':' ; T_COMMA : ',' ; T_PIPE : '||' ; T_DIV : '/' ; T_DOT2 : '..' ; T_EQUAL : '=' ; T_EQUAL2 : '==' ; T_NOTEQUAL : '<>' ; T_NOTEQUAL2 : '!=' ; T_GREATER : '>' ; T_GREATEREQUAL : '>=' ; T_LESS : '<' ; T_LESSEQUAL : '<=' ; T_MUL : '*' ; T_OPEN_B : '{' ; T_OPEN_P : '(' ; T_OPEN_SB : '[' ; T_CLOSE_B : '}' ; T_CLOSE_P : ')' ; T_CLOSE_SB : ']' ; T_SEMICOLON : ';' ; T_SUB : '-' ; T_MOD : '%' ; L_ID : L_ID_PART // Identifier ; L_S_STRING : '\\'' (('\\'' '\\'') | ('\\\\' '\\'') | ~('\\''))* '\\'' // Single quoted string literal ; L_D_STRING : '""' (L_STR_ESC_D | .)*? '""' // Double quoted string literal ; L_INT : L_DIGIT+ ; // Integer L_DEC : L_DIGIT+ '.' ~'.' L_DIGIT* // Decimal number | '.' L_DIGIT+ ; L_WS : L_BLANK+ -> skip ; // Whitespace L_M_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; // Multiline comment L_S_COMMENT : ('--' | '//') .*? '\\r'? '\\n' -> channel(HIDDEN) ; // Single line comment L_FILE : ([a-zA-Z] ':' '\\\\'?)? L_ID ('\\\\' L_ID)* // File path (a/b/c Linux path causes conflicts with division operator and handled at parser level) ; L_LABEL : ([a-zA-Z] | L_DIGIT | '_')* ':' ; fragment L_ID_PART : [a-zA-Z] ([a-zA-Z] | L_DIGIT | '_')* // Identifier part | '$' '{' .*? '}' | ('_' | '@' | ':' | '#' | '$') ([a-zA-Z] | L_DIGIT | '_' | '@' | ':' | '#' | '$')+ // (at least one char must follow special char) | '""' .*? '""' // Quoted identifiers | '[' .*? ']' | '`' .*? '`' ; fragment L_STR_ESC_D : // Double quoted string escape sequence '""""' | '\\\\""' ; fragment L_DIGIT : [0-9] // Digit ; fragment L_BLANK : (' ' | '\\t' | '\\r' | '\\n') ; // Support case-insensitive keywords and allowing case-sensitive identifiers fragment A : ('a'|'A') ; fragment B : ('b'|'B') ; fragment C : ('c'|'C') ; fragment D : ('d'|'D') ; fragment E : ('e'|'E') ; fragment F : ('f'|'F') ; fragment G : ('g'|'G') ; fragment H : ('h'|'H') ; fragment I : ('i'|'I') ; fragment J : ('j'|'J') ; fragment K : ('k'|'K') ; fragment L : ('l'|'L') ; fragment M : ('m'|'M') ; fragment N : ('n'|'N') ; fragment O : ('o'|'O') ; fragment P : ('p'|'P') ; fragment Q : ('q'|'Q') ; fragment R : ('r'|'R') ; fragment S : ('s'|'S') ; fragment T : ('t'|'T') ; fragment U : ('u'|'U') ; fragment V : ('v'|'V') ; fragment W : ('w'|'W') ; fragment X : ('x'|'X') ; fragment Y : ('y'|'Y') ; fragment Z : ('z'|'Z') ; ",16337,True,3383.886363523305,median "FORMAT: 1A HOST: https://tenant.acrolinx.cloud # Acrolinx Platform API The Acrolinx Platform API is the new REST like API for accessing the Core Platform. **NOTE:** All listed (future) features, which aren't yet or only partially implemented, are marked with the keyword DRAFT. Please consider this while using the Acrolinx Platform API! # Authentication and Authorization When using the Acrolinx Platform API, you'll need to be authorized and authenticated. This is done by providing an **Access Token**. An **Access Token** is an encoded and cryptographically signed string. It has the following characteristics: * It's bound to a user * There can be an infinite number of Access Tokens per user * It has a certain lifetime (default 30 days, can be changed) * It will expire after the lifetime or when the password of the associated user is changed * It provides authorization and authentication How to get an **Access Token**? You can get an Access Token by using the Acrolinx sign-in workflow. (further description here) How to use an Access Token? Every request you're doing with the Acrolinx Platform API must contain a [header](#header-access-token) providing the Access Token: ``` X-Acrolinx-Auth: WERTZUIOP ``` ## API Token An API Token is an Access Token but with special characteristics: * It has a lifetime of 4 years * It will **not expire when the password of the associated user is changed** * Only one API Token can be bound to a user at the time You can get an API Token by accessing the user settings page on the Dashboard and generating one. Other than that, the **API Token** functions as an **Access Token**. # General Headers ## Access Token All methods except ""index"" and ""poll access token"" require a valid access token in the `X-Acrolinx-Auth` header even if not explicitly mentioned below. If the token is invalid, a `401` response is returned (see `401` response of ""index"") even if this response isn't explicitly mentioned below. Example: ``` X-Acrolinx-Auth: 123579080a8d1fee12490a90dc3 ``` ## Base URL To support reverse proxies, a client may provide the `X-Acrolinx-Base-Url` header with each request. If the response body to the request contains links into the Acrolinx API, the server will prefix them with the given value. The provided value must be an absolute URL including scheme and host. Malformed values will result in a `400` status code. Example: ``` X-Acrolinx-Base-Url: https://example.com/path/ ``` ## Client Locale All methods accept a header `X-Acrolinx-Client-Locale`, with which the client can identify its own locale (for example, UI language). The value of the header field must be a single language tag that is compliant to BCP 47. The Acrolinx Platform will try to return message strings and other locale-specific parts of the response in the requested language. Example: ``` X-Acrolinx-Client-Locale: de-CH ``` The server tries to match the sent locale to the closest locale that it's able to support, for example, `de`. The ""index"" request returns the list of supported locales. The server falls back to the default `en` locale in the following cases: * no X-Acrolinx-Client-Locale header is sent * there's no matching supported locale * for the given response, there's no appropriate localization available ## Signature If not otherwise documented, all methods require a header `X-Acrolinx-Client` to be set. The header must be a valid signature. The request returns an error, if the header is omitted or the given signature isn't valid. The format of the signature is `Signature;Version;buildNumber`, where `Signature` is the signature as configured in the Acrolinx license and `Version` is the version number of the client. Example: ``` X-Acrolinx-Client: SW50ZWdyYXRpb25EZXZlbG9wbWVudERlbW9Pbmx5; 1.0.1.45 ``` # Response Format The API provides a consistent format for all responses. Each response as a field `links` and one of the three fields `error`, `progress`, `data`. The `links` field contains further URLs that can be used as a next step in the workflow. `error` is set, of the request didn't succeed. This is accompanied by an HTTP status code above or equal 4xx. `progress` means, that the processing isn't yet finished and the client has to poll for the final result. `data` contains the actual result data, the processing is successfully finished. ## Error Responses ### General Format The API provides a consistent format for errors, which is based on [RFC7807](https://datatracker.ietf.org/doc/rfc7807/?include_text=1). The format is JSON and the API guarantees to send the fields `type`, `title`, `detail`, `status` with each error response. Example: ``` HTTP/1.1 403 Forbidden Content-Type: application/problem+json { ""error"": { ""type"": ""auth"", ""title"": ""Invalid authentication"", ""detail"": ""The provided token for authorization is not valid."", ""status"": 403 } ""links"": {} } ``` * `type` is a unique identifier for the type of error. A client may choose a workflow for the error handling depending on the type. * `title` is a short description of the error. It can be displayed to the user as title of the error. * `detail` is a more verbose description of the error. It's suitable to be displayed to the user. * `status` is redundant to the HTTP status code. It may be helpful in case a proxy changed the HTTP status code of the original API response. * An optional `reference` field with an id may be present. If there, this id can be found in the Acrolinx log files to support better problem analysis. Depending on `type`, additional fields may be part of the response providing more detailed information. Additional fields may be added in future. A client must not break because of unexpected fields. ### Error Types Type | Description| What to do -----|------------|------------ `client` | Unspecific error caused by the client's request. | Check logs and configuration or the client code. `server` | Unspecific error during processing of a request in Acrolinx. | Check logs and configuration. `clientSignatureMissing` | The `X-Acrolinx-Client` header was missing. | Contact Acrolinx, how to acquire a valid license. `clientSignatureRejected` | The given signature in the `X-Acrolinx-Client` header was invalid. | Contact Acrolinx, how to acquire a valid license. `sso` | Returned for any single sign-on errors. | Most probably this is a configuration issue. `auth` | Invalid authentication. | Use another access token. `insufficientPrivileges` | Insufficient privileges. | Assign the required privileges to the user. `interactiveSignInTimedOut` | The interactive sign-in process timed out. | Start new. `checkCancelled` | The check was canceled. No result is available. | Probably points to an error in the client. `checkFailed` | The check failed. | Check logs and configuration. `invalidBaseUrl` | The request contained an invalid base URL in the `X-Acrolinx-Base-URL` header. | Check configuration of client or proxies, which set the header. `customFieldsIncorrect` | Custom field values are incorrect. |Please provide valid values for all required custom fields before or when checking a document. `validation` | Invalid request attributes. | Check the request for invalid values or missing parameters. `guidanceProfileDoesntExist` | Guidance profile doesn't exist | The guidance profile doesn't exist or isn't available for the user id and language given. `noGuidanceProfileConfigured` | No guidance profile configured | For the user id and language given no guidance profile is configured. `contentTooLarge` | Content to large | Without reconfiguration of the Acrolinx platfrom the document can't be checked. `queueLimitExceeded` | Queue limit exceeded | Retry to submit the check after waiting at least as long as suggested in the retry-after header. `conflict` | Concurrent write access | Conflict with a concurrent write access. Retry the operation with fresh data. `licenseLimitExceeded` | License limit exceeded | You exceeded a limit set by your licensing terms. The error description contains more details. Please check [the documentation](https://docs.acrolinx.com/coreplatform/latest/en/user-management/user-licenses) for more information. ### Additional Information On Validation Errors Errors with type `validation` come with a list of constraint violation descriptions in an additional property `validationDetails`: ``` { ""title"": ""Validation error"", ""constraint"": ""The 'languageId' is required."", ""attributePath"": ""submit.arg1.languageId"", ""detail"": ""The 'languageId' is required but was 'null'."", ""invalidValue"": ""DictionaryEntry{surface='TestSurface', scope=language, languageId='', guidanceProfileId='null', documentId='null'}"", ""possibleValues"": [""en"", ""de""] } ``` * `title`: ""Validation error"" * `constraint`: A minimal description of the constraint that was violated. * `attributePath`: A hint towards the property or parameter that had an invalid value. * `detail`: A more detailed description of the constraint violation. * `invalidValue`: The value that was invalid. Can be a data structure. * `possibleValues`: An optional list of valid values for the property. The `validationDetails` are intended as information for developers to troubleshoot bad requests. They are not intended for automated consumption. Values are not guaranteed to be always present or in a uniform format. ## Progress Responses A progress response always contains a field `retryAfter`, which tells the client how many seconds to wait until the next poll request. Optionally the response can have the fields `message`, that contains a human user readable text about the current status, and `percent`, that is a number and shows the progress in percent. A progress response has always the `Retry-After` header set with the same value as the `retryAfter` field and an HTTP status 202. Examples: ``` HTTP/1.1 202 Accepted Content-Type: application/json { ""progress"": { ""message"": ""The request is queued on position 5."", ""percent"": 2, ""retryAfter"": 5 } ""links"": { ""cancel"": ""https://tenant.acrolinx.cloud/api/v1/checks/ID100"" } } ``` ``` HTTP/1.1 202 Accepted Content-Type: application/json { ""progress"": { ""retryAfter"": 1 } ""links"": {} } ``` ## Successful Responses The fields of a successful response with data depend on the request. Example: ``` HTTP/1.1 200 Ok Content-Type: application/json { ""data"": { ""score"": 99, ""textualScore"": ""Good job!"" } ""links"": { ""submit"": ""https://tenant.acrolinx.cloud/api/v1/checks"" } } ``` # HTML Fields Responses may have fields, that contain HTML snippets to provide nice formatting in interactive clients. Those fields are clearly marked by a name that ends with Html, for example, guidanceHtml. There may be related field with the same content in plain text. If such a field exists, it ends with Text as for example, guidanceText. All HTML fields contain only undangerous formatting tags that can be used without security risks. All tags are filtered by server-side whitelist. # Group Index ## Index [GET /api/v1] Note: This is the only web service method that provides a 200 response if no access token was sent. If an invalid access token was sent, the response is still a 401, though. + Request + Header X-Acrolinx-Auth: """" + Response 200 (application/json) { ""data"": { ""server"": { ""version"": ""5.1.0.123"", ""name"": ""Acrolinx Core Platform"" }, ""locales"": [ ""en"" ] }, ""links"": { ""signIn"": ""https://tenant.acrolinx.cloud/api/v1/auth/sign-ins"" } } + Request + Header X-Acrolinx-Auth: 123579080a8d1fee12490a90dc3 + Response 200 (application/json) { ""data"": { ""server"": { ""version"": ""5.1.0.123"", ""name"": ""Acrolinx Core Platform"" }, ""locales"": { ""en"" } }, ""links"": { ""signIn"": ""https://tenant.acrolinx.cloud/api/v1/auth/sign-ins"", ""submitCheck"": ""http://tennant.acrolinx.cloud/api/v1/checking/checks"" } } + Response 401 (application/json) { // if provided access token became invalid ""error"": { ""type"": ""auth"", ""title"": ""Invalid access token"", ""detail"": ""The provided token for authorization is invalid."", ""status"": 401 }, ""links"": {} } ## Platform Capabilities [GET /api/v1/capabilities] An aggregation of the capabilities of the APIs subresources. This resource serves a single entry point for clients that need to use more than one feature of the API. + Response 200 (application/json) + Attributes + data (object) + checking (object) - capabilities of the checking resource + document (object) - capabilities of the document resource + links (object) # Group Authentication API Authentication is handled either with a configured access token, with single sign-on (SSO) or in an interactive process by signing in with the Acrolinx sign-in web page. Embedded integrations use either the configured access token or SSO. Interactive clients with a human user use SSO or the interactive process. ## Request/Validate an API Token [POST /api/v1/auth/sign-ins] The sign-in collection allows Acrolinx API clients to request user authentication and to check the validity and privileges of existing access tokens. If the Core Platform is configured for Single Sign-on, this endpoint will accept the configured credentials to authenticate the request. + Request (application/json) + Header X-Acrolinx-Auth: 123579080a8d1fee12490a90dc3 (valid) OR (invalid/expired access token) OR (no access token) X-Acrolinx-Client-Locale: ja X-Acrolinx-Client: QWxlU2hNyb2bHVnLWlunhQyR29Rm9xpbvZ2lZXRz; 1.0.1.45; 12345 + Response 200 (application/json) No sign-in needed, the response body will contain valid access tokens. The server may decide that the request is already sufficiently authorized. In this case, no sign-in process is started. The response will contain the same information as after successful sign-in procedure. The following conditions may lead to this response: - The `X-Acrolinx-Auth` header contained a valid token. - Single Sign-on is configured and valid credentials are supplied. + Attributes (object) + Response 201 (application/json) If the `X-Acrolinx-Auth` header is absent a new sign-in process is started. The response body contains two links. One allows the user to complete the sign-in process. The other helps the client to acquire the session data: - `interactive` a link to a website that allows the user to authenticate and permit the client to access the server. If a language was provided in the `X-Acrolinx-Client-Locale` header, the link will point to a localized version of that website if available and technically possible. - `poll` a link to a resource that will return an *access token* and information about the user after sign-in. (see [GET `api/v1/auth/sign-ins/{id}`](#authentication-api-poll-for-a-new-api-token-get)) Note that the sign-in process will time out. The `interactiveLinkTimeout` field contains the duration in seconds, that the `interactive` link will stay valid. If the Sign-in page was loaded before this time, the server will extend the timeout. To detect timeouts after opening the Sign-in page use the `poll` link. + Body { ""data"": { ""state"": ""Started"", ""interactiveLinkTimeout"": 900 }, ""links"": { ""interactive"": ""https://tenant.acrolinx.cloud/dashboard.html?login=19901-2-8412998412"", ""poll"": ""https://tenant.acrolinx.cloud/api/v1/auth/sign-ins/185-0ijfgklejt2390tui"" } } + Attributes + data + `state`:`Started` (string, required) + `interactiveLinkTimeout`: 900 (number, required) + links + `interactive`: `https://tenant.acrolinx.cloud/dashboard.html?login=19901-2-8412998412` (string, required) + `poll`: `https://tenant.acrolinx.cloud/api/v1/auth/sign-ins/185-0ijfgklejt2390tui` (string, required) + Response 401 (application/json) If invalid SSO credentials are supplied the request is rejected. This occurs when an SSO username is present but the SSO password is wrong or missing or the user couldn't be created. + Header WWW-Authenticate: ACROLINX_TOKEN, ACROLINX_SIGN_IN (, ACROLINX_SSO) + Attributes (object) + Response 503 The server is unable to start a sign-in process at this time. + Header Retry-After: 30 + Attributes (object) ## Poll for a New API Token [GET /api/v1/auth/sign-ins/{id}] This resource lets a client wait for a user to authenticate and authorize it to use the privileged parts of the Acrolinx API. Once the user has completed the sign-in process, it will return a new access token. It can be sent with each API call to prove the privileges and identity owned by the user that signed in. When polling returned a final result, the polling endpoint will disappear and return a `NOT FOUND` status. + Request + Header X-Acrolinx-Client: QWxlU2hNyb2bHVnLWlunhQyR29Rm9xpbvZ2lZXRz; 1.0.1.45 + Parameters + id: `99576707-ed8c-44b6-82b8-c3ced8f349d1` (string, required) - poll-id for the authorization request + Response 200 (application/json) A user has completed the sign-in process and the server has created a new access token. Note that this resource will disappear after this response. + Attributes (object) + Response 202 (application/json) The user hasn't authorized the sign-in yet. Request the same URI again to continue polling. Note that clients should pace themselves by respecting the `Retry-After` header. + Header Retry-After: 2 + Attributes + progress + `retryAfter`: 2 (number, required) + Response 404 (application/json) The server has no knowledge of the polling token. If a valid poll URI was used, the cause for this is a timeout or another poll request may have consumed the credentials. The returned type is `interactive_sign_in_timed_out`, which distinguishes this response from a normal 404 caused by a just wrong URL. + Attributes + error + `type`: `interactive_sign_in_timed_out` (string, required) + `status`: 404 (number, required) + title: `The interactive sign-in process timed out` (string, required) + detail: `The interactive sign-in process timed out. Please start a sign-in.` (string, required) # Group Checking API The API for checking documents. ## List All Checking Methods [GET /api/v1/checking] + Response 200 (application/json) { ""data"":{} ""inputFormats"": [] }, ""links"": { ""submit_check"": ""https://tenant.acrolinx.cloud/api/v1/checking/submit"", ""checking_capabilities"": ""https://tenant.acrolinx.cloud/api/v1/checking/capabilities"", } } ## List Checking Capabilities [GET /api/v1/checking/capabilities] The new checking API replaces writing guides and Content Profiles with a flat list of guidance profiles. Each guidance profile corresponds to a writing guide or a Checking Profile. If Sublanguages are activated, they're folded into the list of guidance profiles. For each guidance profile, the server provides information about the language, activated goals, and term sets. The client may use this for filtering purposes, but they can only select one (complete) guidance profile for checking (for example, not deselect goals). + Response 200 (application/json) { ""data"": { ""guidanceProfiles"": [ { ""id"": ""aud-1"", ""displayName"": ""Tom the Technical Type"", ""language"": { ""id"": ""en-gb"", ""displayName"": ""English (Great Britain)"" }, ""goals"": [{ ""id"": ""spelling"", ""displayName"": ""Spelling"", ""color"": ""#f21"" }, { ""id"": ""voice.readability"", ""displayName"": ""Clarity"", ""color"": ""#f22"" }, { ""id"": ""term.unsuitable"", ""displayName"": ""Unsuitable Term"", ""color"": ""#f23"" }, { ""id"": ""term.admitted"", ""displayName"": ""Use with caution"", ""color"": ""#f24"" }], ""termSets"": [{ ""displayName"": ""Switches"" }, { ""displayName"": ""Acrolinx"" }] }, { ""id"": ""aud-2"", ""displayName"": ""Randolf Redakteur"", ""language"": { ""id"": ""de"", ""displayName"": ""German"" }, ""goals"": [{ ""id"": ""spelling"", ""displayName"": ""Spelling"", ""color"": ""#f21"" }], ""termSets"": [] } ], ""contentFormats"": [ { ""id"": ""auto"", ""displayName"": ""Automatic Detection"" }, { ""id"": ""text"", ""displayName"": ""Plain Text"" }, { ""id"": ""markdown"", ""displayName"": ""Markdown"" }, { ""id"": ""xml"", ""displayName"": ""XML"" }, { ""id"": ""word_xml"", ""displayName"": ""XML (MS Word 2003)"" } ], ""contentEncodings"": [ ""none"", ""zip,base64"", ""base64"" ], ""referencePattern"": ""\\\\.(xml|xhtm|xhtml)$|\\\\.(md|markdown|mdown|mkdn|mkd)$|\\\\.(docx|docm|pptx|pptm|xlsx|xlsm)$|\\\\.txt$"", ""checkTypes"": [ ""batch"", ""interactive"", ""baseline"", ""automated"" ], ""reportTypes"": [""extractedText"", ""termharvesting"", ""scorecard""] } } ## Submit a Check [POST /api/v1/checking/checks] Submits a document for checking. After uploading the document it will be scheduled for analysis. Once Acrolinx is done checking the document all results will be collected and made available. This leads to the following steps when using the check API: * submit a check * poll for progress * download check results For an overview on what documents and file types are supported by Acrolinx please consult the list of [Supported Input Types](https://docs.acrolinx.com/coreplatform/latest/en/compatibility/supported-input-types). The same information is available in the checking capabilities. This call includes an implicit ""create/search for document"" (in case no document id was given) and ""update document"" (in case document id was given). + Request (application/json) A minimal request declaring the format only: { ""content"": ""text to check"", // required ""checkOptions"": { ""contentFormat"": ""markdown"", // optional, default: auto }, } A minimal request using a document reference to tell the format: { ""content"": ""text to check"", // required ""document"": { // optional, default: empty ""document"" object ""reference"": ""C:\\\\abc.md"", // optional, default: do not search for ID, always create } } If a standard format is configured on the server, the minimal request is even shorter: { ""content"": ""text to check"", // required } A request can be much more specific, this is the full set of attributes: { ""content"": ""text to check"", // required ""contentEncoding"": ""base64"", // optional, default: none = HTTP request encoding ""checkOptions"": { ""guidanceProfileId"": ""aud-1"", // optional, default: first guidance profile ""reportTypes"": [""scorecard""], // optional, default: scorecard ""contentFormat"": ""markdown"", // optional, default: auto ""checkType"": ""batch"", // optional, default: interactive // the use case of the check, can be: // interactive = human user checks own document // batch = human user checks many own documents // baseline = a repository of documents is checked, the user doesn't own the documents // automated = check of a single document for automated scenarios as for example a git hook ""partialCheckRanges"": [{ ""begin"": 10, ""end"": 20 }, { ""begin"": 40, ""end"": 70 }], // makes the check a partial check ""batchId"": ""gen.clc.159203590"" // only for batch checks; optional; }, ""document"": { // optional, default: empty ""document"" object ""reference"": ""C:\\\\abc.md"", // optional client known id hint e.g. a file name ""customFields"": [ // optional { ""key"": ""field1"", ""value"": ""value1"" },{ ""key"": ""field2"", ""value"": ""value2"" } ] } } + Response 201 (application/json) { ""data"": { ""id"": ""AB-153"" }, ""links"": { ""result"": ""https://tenant.acrolinx.cloud/api/v1/checking/checks/AB-153"", ""cancel"": ""https://tenant.acrolinx.cloud/api/v1/checking/checks/AB-153"" } } + Response 400 (application/json) { ""error"": { ""detail"": ""The guidance profile doesn't exist or isn't available for the user id and language given."", ""type"": ""content_goal"", ""title"": ""guidance profile doesn't exist"", ""status"": 400 }, ""links"": { } } ## Check Result [/api/v1/checking/checks/{id}] ### Check Result How-To #### Ignore All Issue Occurrences Every issue in the check result has the attribute `positionalInformation.hashes.issue`. You can use this attribute to find all occurrences of an issue. All these issues can be ignored together. The integration can also remember the `positionalInformation.hashes.issue` attribute after an ignore-all operation. This lets you filter out all previously ignored occurrences of an issue after a recheck. #### Replace All Issue Occurrences with a Suggestion Every issue in the check result has the attribute `positionalInformation.hashes.issue`. You can use this attribute to find all occurrences of an issue. To apply a suggestion to all occurrences of an issue, use the `groupId` attribute to find the corresponding suggestion. If an occurrence of an issue doesn’t have a suggestion with the same `groupId` or if the `groupId` is empty, then it can't be replaced with a replace-all operation. Note that not all occurrences of an issue always have the same suggestions. In this case, the replace-all operation only applies to issues with the same suggestion. ### Poll Check Result [GET] Polls the check result. Either a progress or the completed result is returned. The URL for the request is found in the submitted check's ""result"" link. + Parameters + id: `AB-153` (required, string) ... the check id + Response 202 (application/json) + Headers Retry-After: 2 + Body { ""progress"" : { ""percent"": 20, ""message"": ""Waiting in queue"", ""retryAfter"": ""2"" } } + Response 200 (application/json) Attention: which attributes are contained in the response depends on configuration, request and the document. { ""data"":{ ""id"": ""AB-153"", ""checkOptions"": { ""guidanceProfileId"": ""aud_1"", ""guidanceProfileName"": ""Acrolinx Essentials"", ""languageId"": ""en"", ""termSets"": [{ ""displayName"": ""Switches"" }, { ""displayName"": ""Acrolinx"" }], ""reportTypes"": [""scorecard"", ""termharvesting""], ""contentFormat"": ""markdown"", ""checkType"": ""interactive"", ""partialCheckRanges"": [{ ""begin"": ""10"", ""end"": ""20"" }, { ""begin"": ""40"", ""end"": ""70"" }], ""confidential"": false }, ""document"": { ""id"": ""283ab1e075f21a"", # DRAFT ------START------ ""contentType"": ""E-Mail"", # DRAFT ------END------ ""customFields"": [ { ""displayName"": ""Project ID"", ""key"": ""projectId"", ""value"": ""Marketing Campaign"", ""required"": true } ], ""displayInfo"": { ""reference"": ""abc.md"" } }, ""quality"": { ""score"": 57, ""status"": ""red"", ""scoresByStrategy"": [ { ""id"": ""average"", ""score"": 100 }, { ""id"": ""minimum"", ""score"": 100 }], ""scoresByGoal"": [ { ""id"": ""GRAMMAR"", ""score"": 100 }, { ""id"": ""STYLE"", ""score"": 100 }, { ""id"": ""TERMINOLOGY"", ""score"": 100 }, { ""id"": ""INFORMALITY"", ""score"": 100 }, { ""id"": ""READABILITY"", ""score"": 100 }, { ""id"": ""SPELLING"", ""score"": 100 }, { ""id"": ""TERMINOLOGY_ADMITTED"", ""score"": 0 }], ""metrics"": [ { ""id"": ""Clarity index"", ""score"": 100 }, { ""id"": ""Informality index"", ""score"": 47 }, { ""id"": ""Liveliness index"", ""score"": 50 }, { ""id"": ""Flesch Reading Ease"", ""score"": 36 }] }, ""counts"": { ""sentences"": 10, ""words"": 121, ""issues"": 15 }, ""goals"": [ { ""id"": ""SPELLING"", ""displayName"": ""Spelling"", ""color"": ""#ff838b"", ""issues"": 0 }, { ""id"": ""GRAMMAR"", ""displayName"": ""Grammar"", ""color"": ""#97beff"", ""issues"": 0 }, { ""id"": ""STYLE"", ""displayName"": ""Style"", ""color"": ""#70cb9c"", ""issues"": 0 }, { ""id"": ""TERMINOLOGY"", ""displayName"": ""Deprecated Terms"", ""color"": ""#ffc0ff"", ""issues"": 0 }, { ""id"": ""TERMINOLOGY_ADMITTED"", ""displayName"": ""Admitted Terms"", ""color"": ""#90b0fd"", ""issues"": 0 }, { ""id"": ""READABILITY"", ""displayName"": ""Clarity"", ""color"": ""#b77891"", ""issues"": 0 }, { ""id"": ""INFORMALITY"", ""displayName"": ""Conversational Tone"", ""color"": ""#cb3393"", ""issues"": 0 }], ""issues"": [ { ""goalId"": ""spelling"", ""internalName"": ""title_case_chicago"", ""displayNameHtml"": ""Use Chicago style for the title case?"", ""guidanceHtml"": ""
\\n

According to the Chicago Manual of Style, here's how you write titles:

\\n
    \\n
  • Capitalize the first word and the last word.
  • \\n
  • Capitalize all \\""main\\"" words.
  • \\n
  • Don't capitalize articles and conjunctions (example: a, and).
  • \\n
  • Don't capitalize prepositions independent of their length (example: about, around).
  • \\n
\\n
"", ""displaySurface"": ""zentense"", ""canAddToDictionary"" : true, ""positionalInformation"": { ""hashes"": { ""issue"": ""BhKh3iaGBjB7Cw6M/GwrLQ=="", ""environment"": ""vJ9eCVViEpIdM76h+5K/nA=="", ""index"": ""hjlRLT0K+LlvlslKdNUlhw==1"" }, ""matches"": [{ ""extractedPart"": ""zen"", # DRAFT ""extractedBegin"": 30, ""extractedEnd"": 33, ""originalPart"": ""zen"", ""originalBegin"": 19247, ""originalEnd"": 19255 }, { ""extractedPart"": ""te"", # DRAFT ""extractedBegin"": 33, ""extractedEnd"": 35, ""originalPart"": ""&te;"", ""originalBegin"": 19250, ""originalEnd"": 19254 },{ ""extractedPart"": ""nse"", # DRAFT ""extractedBegin"": 35, ""extractedEnd"": 38, ""originalPart"": ""nse"", ""originalBegin"": 19254, ""originalEnd"": 19257 }] }, ""readOnly"": true, ""issueLocations"": [ { ""locationId"": ""pageLocation"", ""displayName"": ""Page 4"", ""values"": { ""page"": ""4"" } } ], ""suggestions"": [ { ""surface"": ""sentence"", ""groupId"": ""sentence"", // the replacements refer to the matches entry of the same Index // null means, don't change, any other value including the empty string means, replace the match ""replacements"": [""sen"",null,""nce""], ""iconId"":""preferred"" // optional icon id for terminology issues, ""preferred"" or ""admitted"" } }], ""links"": { ""termContribution"": ""https://tenant.acrolinx.cloud/terminology/v7/rest/contribute"", ""termContributionInteractive"": ""https://tenant.acrolinx.cloud/termcontribution.html?surface=@@base64:cXdlcnR5dWlvcA==&locale=en&language=en&userid=admin&context=@@base64:VGhpcyBzZW50ZW5jZSBoYXMgYSBxd2VydHl1aW9wLg=="", ""addToDictionary"": ""https://tenant.acrolinx.cloud/api/v1/dictionary/submit"", ""help"":""https://tenant.acrolinx.cloud/htmldata/en/rules/help/title_case_chicago.html"" } }, { ""goalId"": ""term.unsuitable"", ""internalName"": ""term_flag"", ""displayName"": ""Illegal sublanguage variant of preferred term"", ""guidance"": ""
\\n\\tDomains\\n\\t\\t\\t
Switches\\n\\t\\t\\t\\t\\t
\\n\\t\\tNote\\n\\t\\t
\\n\\t\\tUse 'please' in presale materials only. Do NOT use 'please' in postsale material.\\n\\t
\\n"", ""displaySurface"": ""Please"", ""positionalInformation"": { ""hashes"": { ""issue"": ""3qyt/AVxwNTOUQSuMA7brw=="", ""environment"": ""TiwIFBwA6X920mDAezJTyQ=="", ""index"": ""Lm9PqBGGm+tj21rt3pkpjA==1"" }, ""matches"": [{ ""extractedPart"": ""Please"", # DRAFT ""extractedBegin"": 766, ""extractedEnd"": 772, ""originalPart"": ""Please"", ""originalBegin"": 28223, ""originalEnd"": 28229, }], }, ""readOnly"": false, ""issueLocations"": [], ""suggestions"": [ { ""surface"": ""blablub"", ""icon"": ""https://tenant.acrolinx.cloud/tng/icons/preferred.svg"", ""groupId"": ""2653"", ""replacements"": [""blablub"" ] } } ], # DRAFT ------START------ ""debug"": { ""term"": { ""surface"": ""please"", ""status"": ""DEPRECATED"", ""termSets"": [""RA-Terms""], ""domains"": [""RA-Terms""], ""variant"": ""legalVariantIllegal"", } } # DRAFT -------END------- }, { ""goalId"": ""voice.readability"", ""internalName"": ""en-clarity-medium"", ""displayName"": ""Too complex? Your readers need a medium level of clarity. "", ""guidance"": """", ""displaySurface"": ""Reports ... length"", ""positionalInformation"": { ""hashes"": { ""issue"": ""E3OxJ3bFcfWLyAisUxufAA=="", ""environment"": ""XVYQZVyCoFOr1TDeyXuMgg=="", ""index"": ""accsS0dbn/3rafcbT9NJGw==1"" }, ""matches"": [{ ""extractedPart"": ""Reports"", # DRAFT ""extractedBegin"": 1360, ""extractedEnd"": 1367, ""originalPart"": ""Reports"", ""originalBegin"": 33173, ""originalEnd"": 33180, }, { ""extractedPart"": ""length"", # DRAFT ""extractedBegin"": 1749, ""extractedEnd"": 1755, ""originalPart"": ""length"", ""originalBegin"": 33562, ""originalEnd"": 33568, }] }, ""suggestions"": [], ""issueLocations"": [], ""readOnly"": false, ""debug"": { ""penalty"": 1234.0967741949999 }, ""subIssues"": [{ ""goalId"": ""voice.readability"", ""internalName"": ""phenomenon_embedded_or_complex_sentence"", ""displayName"": ""Try to split up this sentence."", ""guidance"": ""

This sentence doesn't seem to flow smoothly. We found a few embedded phrases in there that could be messing with your flow somehow.

"", ""displaySurface"": ""Reports ... length"", ""positionalInformation"": { ""hashes"": { ""issue"": ""7s1nqUN96X+P6VY4FlfSQQ=="", ""environment"": ""XVYQZVyCoFOr1TDeyXuMgg=="", ""index"": ""++0c1Z/OQu1Mwzt0KpkYYA==1"" }, ""matches"": [{ ""extractedPart"": ""Reports"", # DRAFT ""extractedBegin"": 1360, ""extractedEnd"": 1367, ""originalPart"": ""Reports"", ""originalBegin"": 33173, ""originalEnd"": 33180, }, { ""extractedPart"": ""length"", # DRAFT ""extractedBegin"": 1749, ""extractedEnd"": 1755, ""originalPart"": ""length"", ""originalBegin"": 33562, ""originalEnd"": 33568, }] }, ""suggestions"": [], ""issueLocations"": [], ""readOnly"": false, ""debug"": { ""penalty"": 320.0 } }, { ""goalId"": ""voice.readability"", ""internalName"": ""phenomenon_passive"", ""displayName"": ""The active voice is usually clearer."", ""guidance"": ""

This one could do with a bit of pep. It's probably because it feels kind of passive. We love it when you're assertive.

"", ""displaySurface"": ""was first seen"", ""positionalInformation"": { ""hashes"": { ""flag"": ""dg+ih1XodWeL7lJ/wo17QQ=="", ""environment"": ""XVYQZVyCoFOr1TDeyXuMgg=="", ""index"": ""fOJLASZHiwnwcJWcfbkXnw==1"" }, ""matches"": [{ ""part"": ""was"", ""begin"": 33219, ""end"": 33222, ""extractedBegin"": 1406, ""extractedEnd"": 1409 }, { ""part"": ""first"", ""begin"": 33223, ""end"": 33228, ""extractedBegin"": 1410, ""extractedEnd"": 1415 }, { ""part"": ""seen"", ""begin"": 33229, ""end"": 33233, ""extractedBegin"": 1416, ""extractedEnd"": 1420 }] }, ""suggestions"": [], ""issueLocations"": [], ""readOnly"": false, ""debug"": { ""penalty"": 40.0 } }] } ], ""keywords"": { ""links"":{ ""getTargetKeywords"": ""https://tenant.acrolinx.cloud/services/v1/rest/findability/targetKeywords?contextId=C%3A%5CUsers%5Cgrabowski%5CDesktop%5Ccloud-linguistic-smoketest.docx"", ""putTargetKeywords"": ""https://tenant.acrolinx.cloud/services/v1/rest/findability/targetKeywords?contextId=C%3A%5CUsers%5Cgrabowski%5CDesktop%5Ccloud-linguistic-smoketest.docx"" }, ""discovered"": [{ ""keyword"": ""Clarity card"", ""sortKey"": ""10"", ""density"": 0.2546269436736127, ""count"": 4, ""prominence"": 0.0, ""occurrences"": [{ ""matches"": [ // ... ] }], ""warnings"": [] }], ""target"": [] }, ""embed"":[{ // While the below keys represent the current implementation, they can change without notice ""key"": ""timeStarted"", ""value"": ""2018-11-23T07:29:10.979Z[UTC]"" },{ ""key"": ""score"", ""value"": ""84"" },{ ""key"": ""status"", ""value"": ""green"" },{ ""key"": ""scorecardUrl"", ""value"": ""https://tenant.acrolinx.cloud/services/output/en/oi5ilqippevjh2cdyn3hyldiwa_report.html"" }], // DRAFT ------START------ ""addonInfo"": [ { ""id"": ""mightyAddon"", ""title"": ""Mighy Addon by Cool Corp."", ""iconClass"": ""search-icon"", ""iconUrl"": ""..."", ""url"": ""https://mighy.cool.com/addon?fancyId=12345"" } ], // DRAFT -------END------- ""reports"": { ""scorecard"": { ""displayName"":""Score Card"", ""link"": ""https://tenant.acrolinx.cloud/output/en/abcdef_1_report.html"", ""linkAuthenticated"": ""https://tenant.acrolinx.cloud/output/en/abcdef_1_report.html?apikey=hfhfzhfhrz"" }, ""termharvesting"": { ""displayName"": ""Term Harvesting"", ""link"": ""https://tenant.acrolinx.cloud/output/en/termharvesting_1.xml"", ""linkAuthenticated"": ""https://tenant.acrolinx.cloud/output/en//termharvesting_1.xml?apikey=tfhzzhfhrz"" } }, ""dictionaryScopes"": [""language"", ""guidanceProfile"", ""document""] }, ""links"": { } } + Response 400 (application/json) { ""error"": { ""message"": ""Custom field values are missing"", ""type"": ""custom_fields_incorrect"", ""title"": ""Custom field values are incomplete."", ""documentId"": ""3487ahgfh5fg-fg3"", ""validationDetails"": [ { ""title"": ""Custom field is required."", ""constraint"": ""Custom field \\""Field\\"" must not be empty."", ""attributePath"": ""document.customFields.Field"", ""detail"": ""Cannot set custom field \\""Field\\"" as it is required and its value is empty."", ""invalidValue"": null, ""possibleValues"": [""Correct Value 1"",""Correct Value 2""], ""type"": ""Required"" } ], ""status"": 400 }, ""links"": { } } + Response 400 (application/json) // if any of the given custom fields is invalid, a detailed error information is given. { ""error"": { ""detail"": ""The value for document custom field \\""Field\\"" cannot be \\""Wrong Value\\""."", ""type"": ""custom_fields_incorrect"", ""title"": ""Custom field values are incorrect"", ""documentId"": ""3487ahgfh5fg-fg3"", ""validationDetails"": [ { ""title"": ""Custom field of invalid value."", ""constraint"": ""Custom field \\""Field\\"" must not be \\""Wrong Value\\""."", ""attributePath"": ""document.customFields.Field"", ""detail"": ""Cannot set custom field \\""Field\\"" as it is required and its value is empty."", ""invalidValue"": ""Wrong Value"", ""possibleValues"": [""Correct Value 1"",""Correct Value 2""], ""type"": ""InvalidValue"" // InvalidValue, InvalidField, Required, Readonly, Inconsistent } ], ""status"": 400 } } ### Cancel Check [DELETE] Cancels a check. Users can only cancel checks they submitted. The URL for the request is found in the submitted check's ""cancel"" link. + Parameters + id: `153` (required, number) ... the check id + Response 200 (application/json) { ""data"": { ""id"": ""153"" } } ## Get Link to Content Analysis Dashboard [GET /api/v1/checking/{batchId}/contentanalysis] Returns the links to the human readable Content Analytics Dashboard, which aggregates information of all checks belonging to the given batch id. Requires the Reporting.read privilege. The link with API token contains a new privilege token with the right Reporting.read. + Parameters + batchId: `XYZ-10-22-33` (required, string) ... the batch check id + Response 200 (application/json) { ""links"": {}, ""data"": { ""links"": [ { ""linkType"": ""withoutAccessToken"", ""link"": ""https://tenant.acrolinx.cloud/analytics/dashboard/app/entry/run.jsp?jrd_resext=%7Bactive%3A0%2Creslst%3A%5B%7Bname%3A%22%2FAcrolinxReports%2Fstandard%2FContent+Analysis.dsh%22%2C%22param_page%22%3Afalse%2Cver%3A-1%2C%22dsh_params%22%3A%5B%7B%22jrd_params%22%3A%7B%22BatchId%22%3A%22_nice_batch_id_88-xyz%22%2C%22CsBaseUrl%22%3A%22http%3A%2F%2Flocalhost%3A8031%22%2C%22CsOutputPath%22%3A%22%2Foutput%22%7D%7D%5D%7D%5D%7D&jrd_userinfo=%7B%22prefer%22%3A%7B%22rpt_lang%22%3A%22en%22%2C%22enableNLS%22%3Atrue%7D%7D&jrs.language=en"" }, { ""linkType"": ""withAccessToken"", ""link"": ""https://tenant.acrolinx.cloud/analytics/dashboard/app/entry/run.jsp?jrd_resext=%7Bactive%3A0%2Creslst%3A%5B%7Bname%3A%22%2FAcrolinxReports%2Fstandard%2FContent+Analysis.dsh%22%2C%22param_page%22%3Afalse%2Cver%3A-1%2C%22dsh_params%22%3A%5B%7B%22jrd_params%22%3A%7B%22BatchId%22%3A%22_nice_batch_id_88-xyz%22%2C%22CsBaseUrl%22%3A%22http%3A%2F%2Flocalhost%3A8031%22%2C%22CsOutputPath%22%3A%22%2Foutput%22%7D%7D%5D%7D%5D%7D&jrd_userinfo=%7B%22prefer%22%3A%7B%22rpt_lang%22%3A%22en%22%2C%22enableNLS%22%3Atrue%7D%7D&jrs.language=en&apikey=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG11ZCI6ImFjcm9saW54OjA4MTEwYThjNzI3MjQzYTMiLCJuYmYiOjE1MDM5MjcyMzksImlzcyI6ImFjcm9saW54OjA4MTEwYThjNzI3MjQzYTM6NWQyNTQ2NWI5ZTA3NDNiZiIsImV4cCINjYwNTYzOSwidG9rZW5UeXBlIjoidXNlciIsImlhdCI6MTUwNDAxMzYzOSwianRpIjoiMmFmOTQzOWIzZDgyNzMwODAEyMGRiZmRlMmYifQ.Lj0chsnnRTX7IevJNyWMMlCviA6ecYAQ0kacy5EGQz0"" }, { ""linkType"": ""shortWithAccessToken"", ""link"": ""http://localhost:8031/api/batch/123?apikey=eyJ0eXAiOiJKV1QiLCOiJhY3JvbGlueCIsInByaXZpbGVnZXMiOlsiQ2hlY2tpbmdBbmRDbGllbnRzLmRvd25sb2FkUmVwb3J0cyJdLCJuYmYiOjE1Mzc5NTQzMjksImlzcyI6ImFjcm9saW54OjA4MTEwYThjNzI3MjQzYTMiLCJleHAiOjE1MzgxMjcxMjksInRva2VuVHlwZSI6InByaXZpbGVnZXMiLCJpYXQi3MjksImp0aSI6IlZRTVNFUzc0SlRCR0JFVFMyWTVBRjJBU1RNIn0.ltac_6JK0s_uODrqrK3TkaUsZiXfrkamo&X-Acrolinx-Client-Locale=en"" }, { ""linkType"": ""shortWithoutAccessToken"", ""link"": ""http://localhost:8031/api/batch/123?X-Acrolinx-Client-Locale=en"" } ] } } # Group User API Here, a user is an entity that has an id, a sign-in name, name, custom properties (set by client), and custom user information. When custom user information is _required_: * Interactive integrations: This will already be handled via Acrolinx sign-in. Immediately before granting access to client, the user needs to fill out their custom user information. It's thus impossible to obtain an access token for a user with incomplete required custom user information. * Embedded integrations (API key-based): Dashboard access handles this. After signing in to the dashboard, the user needs to fill out their custom user information before getting to the actual dashboard. API tokens can only be obtained in the dashboard for the signed in user. It's thus impossible to obtain an API token for a user with incomplete required custom user information. Security: * A user can read and update its own data * Only privileged users can read or update other users data ## Current User [/api/v1/user/self] Returns information about the current user. See below for possible responses. ## User Resource [/api/v1/user/{id}] + Parameters + id: `eb323701-839f-4998-b56e-3e20c70259c5` (required, string) ... the username ### Get User [GET] + Response 200 (application/json) { ""data"": { ""id"": ""eb323701-839f-4998-b56e-3e20c70259c5"", ""username"": ""fred"", ""fullName"": ""Fred Freelancer"", // ""tenantId"": ""smarttech"", ""properties"" : { ""customkey"": ""customvalue"", }, ""customFields"": [ { ""key"": ""Department"", ""displayName"": ""Department"", ""inputType"": ""optional"", ""type"": ""list"", ""value"": ""My Department"", ""possibleValues"": [ ""No Department"", ""My Department"" ] }, { ""key"": ""external_field"", ""displayName"": ""external_field"", ""inputType"": ""externally_provided"", ""type"": ""text"" } ] } } + Response 401 (application/json) // if access token does not permit to show the user's data { ""error"": { ""detail"": ""The user does not have the required privileges to perform the operation."", ""title"": ""Insufficient privileges"", ""status"": 401 ""type"": ""insufficient_privileges"" } } ### Update User [PUT] + Request (application/json) { ""customFields"": [ { ""key"": ""Department"", ""value"": ""My new Department"", } ] } + Response 200 (application/json) { ""data"": { ""id"": ""eb323701-839f-4998-b56e-3e20c70259c5"", ""username"": ""fred"", ""fullName"": ""Fred Freelancer"", // ""tenantId"": ""smarttech"", ""properties"" : { ""customkey"": ""customvalue"", }, ""customFields"": [ { ""key"": ""Department"", ""displayName"": ""Department"", ""inputType"": ""optional"", ""type"": ""list"", ""value"": ""My new Department"", ""possibleValues"": [ ""No Department"", ""My Department"" ] }, { ""key"": ""external_field"", ""displayName"": ""external_field"", ""inputType"": ""externally_provided"", ""type"": ""text"" } ] } } + Response 400 (application/json) // if any of the updated fields is invalid, a detailed error information is given. { ""error"": { ""detail"": ""Please provide values for all required custom fields."", ""type"": ""validation"", ""title"": ""Custom field values are missing"", ""validationDetails"": [ { ""title"": ""Custom field is required."", ""constraint"": ""Custom field \\""Field\\"" must not be empty."", ""attributePath"": ""customFields.Field"", ""detail"": ""Cannot set custom field \\""Field\\"" as it is required and its value is empty."", ""invalidValue"": null, ""type"": ""Required"" } ], ""status"": 400 } } + Response 401 (application/json) // if access token does not permit to update the user's data { ""error"": { ""detail"": ""The user does not have the required privileges to perform the operation."", ""title"": ""Insufficient privileges"", ""status"": 401 ""type"": ""insufficient_privileges"" } } # Group Document API Here, a document is an entity that associates names/characteristics that identify a document with an ID. It also contains the custom document information. Typical program flow: 1. A document is opened in the host editor. 2. The integration uses create or retrieve document information, to check if the custom fields have to be filled out. If the user has to fill out custom fields, the API returns all fields to fill out and the set values. 3. The integration requests the user to fill out the custom field. 4. The integration sets the new custom fields either using the update document function or while submitting a check request. ## Document [/api/v1/document/{id}] ### Get Document [GET] This method provides Document which was found in the database. + Response 200 (application/json) { ""data"": { ""id"": ""283ab1e075f21a"", ""reference"": ""C:\\\\abc.md"", ""contentType"": ""E-Mail"", ""customFields"": [ { ""displayName"": ""Project ID"", ""key"": ""projectId"", ""value"": null, ""required"": true } ], ""displayInfo"": { ""reference"": ""abc.md"" } } } ### Update Document Custom Fields [PUT] + Request (application/json) { ""reference"": ""C:\\\\abc.md"", ""contentType"": ""E-Mail"", ""customFields"": [ { ""key"": ""projectId"", ""value"": ""Marketing Campaign"" } ], ""displayInfo"": { ""reference"": ""abc.md"" } } + Response 200 (application/json) { ""data"": { ""id"": ""283ab1e075f21a"", ""reference"": ""C:\\\\abc.md"", ""contentType"": ""E-Mail"", ""customFields"": [ { ""displayName"": ""Project ID"", ""key"": ""projectId"", ""value"": ""Marketing Campaign"", ""required"": true } ], ""displayInfo"": { ""reference"": ""abc.md"" } } } ## Document API Capabilities [GET /api/v1/document/capabilities] Use this method to discover the configuration and capabilities of the document API. Available information includes the configured document custom fields. + Response 200 (application/json) + Attributes + data (object) + links (object) # Group Dictionary API This API handles the spelling dictionary. Items listed in the spelling dictionary are ignored (not flagged) by the spelling checker. ## Dictionary Entry From an API perspective, an ""item"" or *dictionary entry* has the following properties: * `surface`: The string that isn't a spelling issue. * `scope`: The range of influence of the spelling exception. * `language` * `guidanceProfile` * `document` * `languageId`: The language in which the surface shouldn't be a spelling issue. * `guidanceProfileId`: The guidanceProfile for which the surface shouldn't be a spelling issue. * `documentId`: The document in which the surface shouldn't be a spelling issue. Depending on the `scope`, the -`Id`-values are optional or mandatory: * `scope=language` requires a `languageId` (or alternatively an `guidanceProfileId`). * `scope=guidanceProfile` requires an `guidanceProfileId`. * `scope=document` requires a `documentId` and alternatively a `languageId` or an `guidanceProfileId`. The `documentId` is a persistent identifier of the document from the Acrolinx Analytics reporting database. (Tip: With an `guidanceProfileId` and a `documentId` you're always on the safe side.) (Tip: guidance profiles have languages. Keep `languageId` and `guidanceProfileId` consistent in that respect if sending both. Otherwise the winner depends on the `scope`.) ## Get Dictionary Capabilities [GET /api/v1/dictionary/capabilities] This method enables the integration to discover the available dictionary scopes. (The availability of scopes depends on the server configuration and the user's privileges.) Alternatively, you can retrieve the available scopes from a check result: ``` data.dictionaryScopes: [ ""language"", ""guidanceProfile"", ""document"" ] ``` + Response 200 (application/json) { ""data"": { ""scopes"": [ ""language"", ""guidanceProfile"", ""document"" ] } } ## Add to Dictionary [POST /api/v1/dictionary/submit] Create a dictionary entry for the specified scope. Beware: Spell checking is a multifaceted functionality. Whether or not a particular issue will disappear after adding it to the dictionary, depends on the issue's true nature. The spelling checker tells you if you can reasonably suppress an issue by adding a surface to the dictionary. In the check result: ``` issues[n].canAddToDictionary: true ``` + Request (application/json) { ""surface"": ""wiruwaruwolz"", // required ""scope"": ""document"", // required, one of the scopes above ""languageId"": ""en_GB"", // required if scope!=guidanceProfile ""guidanceProfileId"": ""aud-1"", // required if scope=guidanceProfile ""documentId"": ""283ab1e075f21a"" // required if scope=document } + Response 200 { ""data"": { ""surface"": ""wiruwaruwolz"", ""scope"": ""document"", ""languageId"": ""en_GB"", ""guidanceProfileId"": null, ""documentId"": ""283ab1e075f21a"" } } # Group Broadcast API - DRAFT You can use platform notifications to inform users that checking might be affected by server maintenance or planned server outages. ## Create a Platform Notification [POST /api/v1/broadcasts/platform-notifications] Publishes a new notification on the platform. + Request (application/json) { ""title"": ""Important Announcement"", // required; The title of the notification ""body"": ""Acrolinx Platform 5.6 will be deployed tomorrow."", // required; Notification text. ""importance"": ""HIGH"", // optional; ""HIGH""|""NORMAL"" ""start"": 1528127782, // required; Notification start time (epoch millisecond timestamp) ""end"": 1530719782 // required; Notification end time (epoch millisecond timestamp) } + Response 201 (application/json) { ""data"": { ""id"": ""e06491e9-c67f-4da7-85da-eb30b9ca9101"" } } ## Retrieve Platform Notifications [GET /api/v1/broadcasts/platform-notifications/{lastRequestTimeInMilliseconds}] Retrieves active notifications from the platform. + Parameters + lastRequestTimeInMilliseconds: `1525449382` (long, required) - epoch millisecond timestamp used to filter active notifications + Response 200 (application/json) { ""data"": { ""requestTimeInMilliseconds"" : ""1525449382"", ""platformNotifications"": [{ ""id"": ""e06491e9-c67f-4da7-85da-eb30b9ca9101"", ""title"": ""Important Announcement"", ""body"": ""Acrolinx Platform 5.6 will be deployed tomorrow."", ""importance"": ""HIGH"", ""start"": 1528127782, ""end"": 1530719782 } ] }} } # Group Monitoring API **Since Core Platform 2019.10** The resources in this group provide information about the health and performance of the Acrolinx Platform. Accessing this information requires the permission ""Access to monitoring API."" This privilege isn’t granted to all users. Make sure the user associated with your API token has the requisite roles. For a quick check of your permissions see if the [metrics index](#monitoring-api-get-available-metrics) contains links. More information about permission management can be found in the [Acrolinx documentation](https://docs.acrolinx.com/coreplatform/latest/en/user-management). ## Get Available Metrics [GET /api/v1/monitoring] Lists available metrics according to the permissions of the API user. If access is granted a link to the metrics resource will be added to the links hash. The following relations are currently available: |Key | Target |----------------|----------------- |`checkMetrics` |[check monitoring resource](#monitoring-api-get-check-metrics) |`healthMetrics` |[server health monitoring resource](#monitoring-api-get-health-metrics) + Response 200 (application/json) { ""links"": { ""checkMetrics"": ""/api/v1/monitoring/checks"", ""healthMetrics"": ""/api/v1/monitoring/health"" } } ## Get Check Metrics [GET /api/v1/monitoring/checks] Provides a summary of the check activity on the Acrolinx Platform. |Field |Contents |-------------------------|------------------- |`receivedChecks` |Total number of checks received by the platform. |`successfulChecks` |Total number of completed checks that didn’t result in an error. |`failedChecks` |Total number of completed checks that resulted in an error. |`unparseableDocuments` |Total number of checks that failed due to parsing errors. |`currentQueueLength` |Current number of checks waiting for a free language server. |`totalQueueTime` |Total time, in seconds, check requests waited for a free language server. + Response 200 (application/json) + Attributes (object) + data (object) + receivedChecks: 54132 (number) - Total number of checks received + successfulChecks: 54130 (number) - Total number of successful checks + failedChecks (number): 2 - Total number of failed checks + unparseableDocuments: 2 (number) - Total number of checks failed due to parsing errors + currentQueueLength: 0 (number) - Current number of waiting checks + totalQueueTime: 1563 (number) - Total time checks spent waiting ## Get Health Metrics [GET /api/v1/monitoring/health] A general summary of the health of the Acrolinx Platform. |Field |Contents |-------------------------|------------------- |`languagesReady` |A hash containing all configured languages as keys. If Acrolinx is ready to check in a language its value will be true. + Response 200 (application/json) { ""data"": { ""languagesReady"": { ""en"": true, ""fr"": true, ""ja"": false } } # Group Other Methods in Existing API - DRAFT Checking API: * Contribute as Term (may be moved to Terminology API) Core Service: * get broadcast messages - integrate into ""index"" call? * is user self-registration enabled - integrate into ""index"" call? * create user - not needed right now? should be part of User API Findability: * get/update target keywords - may link to existing methods? * get keyword info - maybe link to existing method for now? ExtraInfo API: * get extra info tab infos - maybe link to existing methods in ""index"" call for now? Checking Profiles: * get and update user settings? get and update profile user settings? what is this? Feedback API: * submit issue feedback - will be reimplemented anyway Reuse API: * deprecated anyway Debug API: * not needed for now - special use case ",16143,True,2854.46008968297,median ":Namespace TestAllv3 (⎕IO ⎕ML ⎕WX)←1 0 3 StopOnError←0 show←0 ⍝ here be dragons Report←{⍵≠1: 'Failed: ',(2⊃⎕xsi),'[',(⍕2⊃⎕lc),']'⋄ } Assert←{⍺≡⍵:1 ⋄ Error 'Failed: ',(2⊃⎕xsi),'[',(⍕2⊃⎕lc),']' } ∇ r←Error arg :If show ⎕←arg :EndIf Errors,←⊂arg arg ⎕SIGNAL StopOnError/11 r←0 ∇ ∇ Log arg :If show ⎕←arg :EndIf ∇ ∇ At s ⎕DL 60|(s-6⊃⎕TS) ⎕TS ∇ ∇ r←apltype utf8 len;b;us;d r←'' b←127 2047 65535 2097151 67108863 2147483647 us←1 2 3 4 5 6 d←1 2 2 4 4 4 :Select apltype :Case 80 r←⎕UCS len↑(,⍉0 1∘.+1↑b),?len⍴255 :Case 160 r←⎕UCS len↑(,⍉0 1∘.+2↑b),(3⊃b),?len⍴65535 :Case 320 ⍝r←320 ⎕dr len↑ (,⍉0 1 ∘.+5↑b),(6⊃b) , ?len⍴2147483647 r←⎕UCS len↑(,⍉0 1∘.+3↑b),1114111,?len⍴1114111 :Else ⎕SIGNAL 11 :EndSelect ∇ ∇ MakeFile(name size data);nopen;tie nopen←{ ⍝ handle on null file. 0::⎕SIGNAL ⎕EN ⍝ signal error to caller. 22::⍵ ⎕NCREATE 0 ⍝ ~exists: create. ⍵ ⎕NTIE 0 ⍝ exists: tie. } tie←nopen name 0 ⎕NRESIZE tie (size⍴data)⎕NAPPEND tie ⎕NUNTIE tie ∇ ∇ cp←CertPath;instpath instpath←2 ⎕NQ'.' 'GetEnvironment' 'DYALOG' cp←instpath,'/TestCertificates/' ∇ ∇ cert←ReadCert relfilename;fn fn←CertPath,relfilename cert←⊃#.DRCShared.X509Cert.ReadCertFromFile fn,'-cert.pem' cert.KeyOrigin←'DER' (fn,'-key.pem') ∇ ∇ r←name DisplayCert z;dc;nc ⍝ Display information about a certificate dc←{,[1.5](2⊃⍵)[1 2 3 4 5 6]} nc←,[1.5]name'Version' 'SerialNo' 'Subject' 'Issuer' 'ValidFrom' 'ValidTo' dc←{⍵.(Formatted.(Version SerialNo Subject Issuer),Elements.(ValidFrom ValidTo))} :If 0=1⊃z :AndIf 0<⊃⍴2⊃z r←nc,' '⍪⍉↑dc¨2⊃z :Else ⋄ r←('Unable to retrieve ',name)z :EndIf ∇ ∇ r←TestSimple(prot secure);srvx509;cltx509;Port;c;Host;srv;clt;DefaultWaitTime;rs;con;srvcert;cltcert;pa;la r←1 Port←5000 Host←'localhost' srv←'S1' clt←'C1' DefaultWaitTime←5000 Cert←{(⍺.Cert)⍺⍺ ⍵.Cert} r∧←0 Assert⊃c←#.DRC.SetProp'.' 'EventMode' 0 :If secure srvx509←ReadCert'server/localhost' cltx509←ReadCert'client/client' r∧←0 Assert⊃c←#.DRC.SetProp'.' 'RootCertDir'(CertPath,'ca') :else srvx509←cltx509←⍬ :EndIf r∧←0 srv Assert c←#.DRC.Srv srv''Port,((prot≢'')/⊂('Protocol'prot)),secure/('X509'srvx509)('SSLValidation'(64)) r∧←0 clt Assert c←#.DRC.Clt clt Host Port,((prot≢'')/⊂('Protocol'prot)),secure/('x509'cltx509)('SSLValidation'(0)) r∧←0 Assert⊃c←#.DRC.Send clt'Request1' r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷rs←#.DRC.Wait srv DefaultWaitTime con←2⊃rs :If secure Log'Server Certificate'DisplayCert srvcert←#.DRC.GetProp clt'PeerCert' Log'Client Certificate'DisplayCert cltcert←#.DRC.GetProp con'PeerCert' r∧←(2 1⊃srvcert)Assert Cert 2 1⊃#.DRC.GetProp con'OwnCert' r∧←(2 1⊃cltcert)Assert Cert 2 1⊃#.DRC.GetProp clt'OwnCert' :EndIf r∧←0 'Receive' 'Request1'Assert(⊂1 3 4)⌷rs←#.DRC.Wait srv DefaultWaitTime r∧←0 Assert⊃c←#.DRC.Respond(2⊃rs)(⌽4⊃rs) r∧←0 'Receive'(⌽'Request1')Assert(⊂1 3 4)⌷rs←#.DRC.Wait clt DefaultWaitTime r∧←0 Assert⊃pa←#.DRC.GetProp clt'PeerAddr' r∧←0 Assert⊃la←#.DRC.GetProp con'LocalAddr' r∧←(2 2⊃la)Assert 2 2⊃pa r∧←0 Assert⊃la←#.DRC.GetProp clt'LocalAddr' r∧←0 Assert⊃pa←#.DRC.GetProp con'PeerAddr' r∧←(2 2⊃la)Assert 2 2⊃pa r∧←0 Assert⊃c←#.DRC.Close clt r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷rs←#.DRC.Wait srv DefaultWaitTime r∧←(,⊂srv) Assert #.DRC.Names'.' r∧←0 Assert⊃c←#.DRC.Close srv ∇ ∇ r←TestRaw;port;data;size;rs;c1;type;mode;c port←5000 to83←{⍵-256×⍵>127} r←1 :For mode :In 'Raw' 'Blkraw' r∧←0 'S1'Assert c←#.DRC.Srv'S1' ''port mode(40+2*21) r∧←0 'C1'Assert c←#.DRC.Clt'C1' 'localhost'port mode(40+2*21) r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c1←#.DRC.Wait'S1' 5000 :For type :In 83 163 :For size :In ,(2*1+⍳20)∘.+¯1 0 1 data←(-⎕IO)+size⍴⍳256 r∧←0 Assert 1⊃c←#.DRC.Send'C1'(type{⍺=83:to83 ⍵ ⋄ ⍵}data) rs←0 :While (rs S1 CON00000000 X00000000 cnx←{cons[;1]⍳('.'names ⍵)[2]} ⍝ order←1 last←0 :If (0 name)Assert c←#.DRC.Srv name''port :If ready 0=⊃c←#.DRC.SetProp name'ReadyList' 1 :EndIf :While 1 c←#.DRC.Waitt name 10000 :Select 1⊃c :Case 0 :Select 3⊃c :Case 'Error' ix←cnx 2⊃c :If 1119=4⊃c cons[ix;3]←0 :Else cons[ix;3]←4⊃c Log'Server ',(2⊃c),' Error ',⍕3⊃c :EndIf :Case 'Receive' ix←cnx 2⊃c order←last≤5 2⊃c last←5 2⊃c Log'Server received ',(2⊃c) :If 'Control'≡3⊃'.'names 2⊃c c1←#.DRC.Respond(2⊃c)(Control c) :Else c1←#.DRC.Respond(2⊃c)(⌽4⊃c) :EndIf :If 0=⊃c1 cons[ix;2]+←1 :Else Log'Server Respond failed ',c1 :EndIf :Case 'Connect' :If (ix←cnx 2⊃c)>⊃⍴cons cons⍪←(2⊃('.'names 2⊃c))1 ¯1 Log'Server New connection ',(2⊃c) :Else Log'Server same connection ',(2⊃c) :EndIf :EndSelect :Case 100 Log'Server timeout' :Continue :Case 1010 Log Control 4⍴⊂'STAT' :Leave :Else c r←0 :Leave :EndSelect :EndWhile :Else c r←0 :EndIf ∇ ∇ ServerThread(name n m ready);c;cons;cmds;names;cnx;cmx;order;last;ix;c1;r r←1 cons←(0 2)⍴0 cmds←n m⍴0 names←{1↓¨(⍺=⍺,⍵)⊂⍺,⍵} ⍝ 'S1.CON00000000.X00000000 => S1 CON00000000 X00000000 cnx←{cons[;1]⍳('.'names ⍵)[2]} ⍝ cmx←{⍎¯8↑3⊃'.'names ⍵} order←1 last←0 :If 0 'S1'Assert c←#.DRC.Srv name'' 5000 :If ready r∧←0=⊃c←#.DRC.SetProp name'ReadyList' 1 :EndIf :While 1 c←#.DRC.Waitt name 10000 :Select 1⊃c :Case 0 :Select 3⊃c :Case 'Error' ix←cnx 2⊃c :If 1119=4⊃c cons[ix;2]+←1 :Else cons[ix;2]+←100 Log'Server ',(2⊃c),' Error ',⍕3⊃c :EndIf :Case 'Receive' ix←cnx 2⊃c order←last≤5 2⊃c last←5 2⊃c Log'Server received ',(2⊃c) c1←#.DRC.Respond(2⊃c)(⌽4⊃c) :If 0=⊃c cons[ix;2]+←1 cmds[ix;cmx 2⊃c]+←1 :Else ∘∘∘ :EndIf :Case 'Connect' :If (ix←cnx 2⊃c)>⊃⍴cons cons⍪←(2⊃('.'names 2⊃c))1 Log'Server New connection ',(2⊃c) :Else cons[ix;2]+←100 Log'Server same connection ',(2⊃c) :EndIf :EndSelect :Case 100 Log'Server timeout' :Continue :Case 1010 :If ~res,←0=+/(cons[;2]≠2+m) (cons[;2]≠2+m)/cons[;1] :EndIf :If ~res,←∧/∧/cmds +/cmds≠1 :EndIf :If ~res,←order 'Out of order' :EndIf :Leave :Else c r←0 :Leave :EndSelect :EndWhile :Else c r←0 :EndIf ∇ ∇ r←CmdWait cmd;c r←0 waitfor←{100=1⊃cw←#.DRC.Wait ⍺ 10000:⍺ ∇ ⍵ (2⊃⍵)≡⍵[1]⌷4↑cw:0 cw} :If 0=1⊃r←#.DRC.Send cmd cmd ⍝ 3 ⍝ r∧←1≡c←cmd waitfor(1 3 4)(0 'Sent' 0) :AndIf 0=⊃r←cmd waitfor(1 3 4)(0 'Receive'(⌽cmd)) r←0 :Else Log'Client ',cmd,' failed ',r ⍝ r is set :EndIf ∇ ∇ {r}←m Client name;cmds;r;c r←0 :If 0=1⊃r←#.DRC.Clt name'localhost' 5000 cmds←(⊂name,'.'),¨'X',¨8{(-⍺)↑(⍺⍴'0'),⍕⍵}¨⍳m :If ∧/0≡¨r←CmdWait¨cmds Log'Client'name :EndIf c←#.DRC.Close name :Else r←0 Log'Client ',name,' Failed to connect' :EndIf res,←0=⊃r ∇ ∇ r←TestPause;sid;port;cons;cmds;c r←1 show←0 (port cons cmds)←5000 10 2 sid←Server&'S1' 0 0 port {}CControl'START'port c←⎕TSYNC(⊂cmds port)Client1&¨cons⍴⊂'' r∧←∧/0≡¨⊃¨c ⍝ Pause = 1 mean keep socket open but do not accept new connection in conga ⍝ Pause = 2 mean close socket create new socket when resuming. r∧←0 Assert⊃#.DRC.SetProp'S1' 'Pause' 2 c←⎕TSYNC(⊂cmds port)Client1&¨cons⍴⊂'' r∧←∧/1=¨⊃¨c r∧←0 Assert⊃#.DRC.SetProp'S1' 'Pause' 0 c←⎕TSYNC(⊂cmds port)Client1&¨cons⍴⊂'' r∧←∧/0≡¨⊃¨c c←CControl'STAT'port {}##.DRC.Close'S1' ⎕TSYNC sid Report r ∇ ∇ r←TestReadyList2 arg;n;m;ready;cons;ts;tc;tlist n m ready show←arg,(⍴arg)↓2 4 1 0 {}#.DRC.Close¨#.DRC.Names'.' res←⍬ r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 2 r∧←0 2 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' cons←'C',¨8{(-⍺)↑(⍺⍴'0'),⍕⍵}¨⍳n ts←ServerThread&'S1'n m ready ⎕DL 1 tc←m Client&¨cons :While ∨/tc∊⎕TNUMS ⍝ wait for all client threads to finish ⎕DL 0.5 :EndWhile ⎕TSYNC tc r∧←0 Assert⊃c←#.DRC.Close'S1' ⎕TSYNC ts ⍝test :If ~r∧←∧/res res :EndIf Report r ∇ ∇ r←TestReadyList arg;n;m;c;cons;cmds;res;name;data;recv;sendrecv;todo;tlist;i;ci;disconnect;connect;respond;ready;send;recvm;sendm;rs;rr;rt;respondm;last;timing;waitfor;results;show;log n m ready show←arg,(⍴arg)↓2 4 1 0 r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 2 r∧←0 2 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 ⍝('ReadyList' 1) show/'Server Started ',('failed' 'ok')[⎕IO+r] :If ready r∧←0 Assert⊃c←#.DRC.SetProp'S1' 'FIFOMode' 1 :EndIf results←3 2⍴(1 3 4)(0 'Connect' 0)(1 3 4)(0 'Error' 1119)(1 3)(0 'Receive') cons←'C',¨8{(-⍺)↑(⍺⍴'0'),⍕⍵}¨⍳n cmds←'X',¨8{(-⍺)↑(⍺⍴'0'),⍕⍵}¨⍳m log←{show/(40↑⍺),('failed' 'ok')[⎕IO+⍵]} waitfor←{(2⊃⍵)≡⍵[1]⌷c←#.DRC.Wait ⍺ 1000:1 ⋄ c} connect←{0=1⊃c←#.DRC.Clt ⍵'localhost' 5000:1 ⋄ 1111=1⊃c:∇ ⍵ ⋄ 0≠1⊃c:c} disconnect←{0≠⊃c←#.DRC.Close ⍵:c ⋄ 1} name←{(⊃cons[1⊃⍵]),'.',⊃cmds[2⊃⍵]} data←{'Test ',,⍕⍵} send←{0≠⊃#.DRC.Send(name ⍵)(data ⍵)3:¯1 0 'Sent' 0≢(⊂1 3 4)⌷c←#.DRC.Wait(name ⍵)10000:¯2 1 } recv←{100=⊃z←#.DRC.Wait(name ⍵)100000:∇ ⍵ 0 'Receive'(⌽data ⍵)≡(⊂1 3 4)⌷z:1 ¯2} sendm←{(⍵⌷rs)←send ⍵} recvm←{(⍵⌷rr)←recv ⍵} sendrecv←{0≠⊃#.DRC.Send(name ⍵)(data ⍵):¯1 (⍵⌷res)←recv ⍵} respond←{0 'Receive'≢(⊂1 3)⌷c←#.DRC.Waitt'S1' 10000:¯1 ⍝(1<⍴,⍵)∧((data ⍵)≢4⊃c):¯2 ⍝⎕←4⊃c 0≠⊃cr←#.DRC.Respond(2⊃c)(⌽4⊃c):¯3 timing,←5 2⊃c 1 } respondm←{(⍵⌷rt)←respond ⍵} todo←{⍵[(⍴⍵)?⍴⍵]},⍳n m 'Client connect 'log r∧←∧/1≡¨c←connect¨cons ⍝ Client connect 'Server connections 'log r∧←∧/1≡¨c←((⍴cons)⍴⊂'S1')waitfor¨⊂results[1;] ⍝ Server side wait for connection rs←rr←rt←n m⍴0 timing←⍬ {}sendm¨todo ⍝ Client send all commands 'Send 'log r∧←∧/∧/rs=1 tlist←recvm&¨todo ⍝ Client wait for all answers Threaded {}respondm¨todo ⍝ Server respond all commands 'Respond 'log r∧←∧/∧/rt=1 :While ∨/tlist∊⎕TNUMS ⍝ wait for all client threads to finish ⎕DL 0.5 :EndWhile 'Recv 'log r∧←∧/∧/rr=1 'In Order 'log r∧←∧/{0≤(1↓⍵)-¯1↓⍵}timing 'Disconnect 'log r∧←∧/1≡¨c←disconnect¨cons ⍝ close all client connections 'Disconnected 'log r∧←∧/1≡¨c←((⍴cons)⍴⊂'S1')waitfor¨⊂results[2;] ⍝ Server side wait for connectiona to close r∧←0 Assert⊃c←#.DRC.Close'S1' Report r ∇ ∇ r←TestEndpoints;c;EndPoints;Allowed;ep r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 2 r∧←0 2 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 Assert⊃c←#.DRC.GetProp'.' 'TCPLookup' '' 80 EndPoints←⍬~⍨{'IPv6'≡1⊃⍵:(1⊃⍵)(1↓¯4↓2⊃⍵) ⋄ 'IPv4'≡1⊃⍵:(1⊃⍵)(¯3↓2⊃⍵) ⋄ ⍬}¨2⊃c Allowed←((⍴EndPoints)⍴1 0)/EndPoints r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 'S2'Assert c←#.DRC.Srv'S2' '' 5001 'BlkText' 10000('Magic'(#.DRC.Magic'TRex'))('AllowEndpoints'(↓{(⊃⍺)(¯1↓⊃,/(2⊃¨Allowed[⍵]),¨('/29,' '/120,')[⎕IO+⍺≡⊂'IPv6'])}⌸1⊃¨Allowed)) :For ep :In EndPoints r∧←0 Assert⊃c←#.DRC.Clt'C1'(2⊃ep)5000 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 Assert⊃c←#.DRC.Clt'C2'(2⊃ep)5001 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 :If ∨/Allowed∊⊂ep r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'S2' 100 r∧←0 Assert⊃c←#.DRC.Close'C2' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('S2')100 :Else r∧←100 'TIMEOUT'Assert(⊂1 2)⌷c←#.DRC.Wait'S2' 100 r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('C2')100 :EndIf ⍝#.DRC.GetProp(2⊃c)'PeerAddr' r∧←0 Assert⊃c←#.DRC.Close'C1' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('S1')100 :EndFor r∧←0 Assert⊃c←#.DRC.Close'S1' r∧←0 Assert⊃c←#.DRC.Close'S2' Report r ∇ ∇ r←TestSentCompleteText;c1;c;c2;c3 r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 3 r∧←0 3 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 'C1'Assert c←#.DRC.Clt'C1' 'localhost' 5000 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 Assert⊃c1←#.DRC.Send'C1' 'test 1 1' r∧←0 Assert⊃c2←#.DRC.Send'C1' 'test 1 2' 3 r∧←0 Assert⊃c3←#.DRC.Send'C1' 'test 1 3' 3 r∧←0 'Sent' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 'Block' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃c)(4⊃c) r∧←0 'Block' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃c)(4⊃c) r∧←0 'Block' 'test 1 3'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃c)(4⊃c) r∧←0 'Sent' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 'Block' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 'Block' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 'Block' 'test 1 3'Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 Assert⊃c←#.DRC.Close'C1' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('S1')100 r∧←0 Assert⊃c←#.DRC.Close'S1' Report r ∇ ∇ r←TestSentCompleteCMD;c1;c;c2;c3 r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 3 r∧←0 3 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 r∧←0 'C1'Assert c←#.DRC.Clt'C1' 'localhost' 5000 r∧←0 Assert⊃c1←#.DRC.Send'C1' 'test 1 1' r∧←0 Assert⊃c2←#.DRC.Send'C1' 'test 1 2' 3 r∧←0 Assert⊃c3←#.DRC.Send'C1' 'test 1 3' 3 r∧←0 'Sent' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Respond(2⊃c)(4⊃c) r∧←0 'Receive' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Respond(2⊃c)(4⊃c) r∧←0 'Receive' 'test 1 3'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Respond(2⊃c)(4⊃c) r∧←0 'Receive' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c1)100 r∧←0 'Receive' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 r∧←0 'Receive' 'test 1 3'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c3)100 r∧←0 Assert⊃c←#.DRC.Close'C1' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('S1')100 r∧←0 Assert⊃c←#.DRC.Close'S1' Report r ∇ ∇ r←TestThreaded;c2;c1;c3 r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 4 r∧←0 4 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 r∧←0 Assert⊃c←#.DRC.SetProp'S1' 'ConnectionOnly' 1 r∧←(0(,1))Assert c←#.DRC.GetProp'S1' 'ConnectionOnly' r∧←0 'C1'Assert c←#.DRC.Clt'C1' 'localhost' 5000 r∧←0 Assert⊃c←#.DRC.Send'C1' 'test 1 1' r∧←0 Assert⊃c←#.DRC.Send'C1' 'test 1 2' r∧←0 'C2'Assert c←#.DRC.Clt'C2' 'localhost' 5000 r∧←0 Assert⊃c←#.DRC.Send'C2' 'test 2 1' r∧←0 Assert⊃c←#.DRC.Send'C2' 'test 2 2' r∧←0 'C3'Assert c←#.DRC.Clt'C3' 'localhost' 5000 r∧←0 Assert⊃c←#.DRC.Send'C3' 'test 3 1' r∧←0 Assert⊃c←#.DRC.Send'C3' 'test 3 2' 1 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c1←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c1)100 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c2←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 2 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c3←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 3 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c3)100 r∧←100 'TIMEOUT' ''Assert c←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c1)100 r∧←0 'Receive' 'test 2 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 c←#.DRC.Wait(2⊃c3)100 :If 0 'Error' 1119≡(⊂1 3 4)⌷c c←#.DRC.Wait(2⊃c3)100 :EndIf r∧←0 'Receive' 'test 3 2'Assert(⊂1 3 4)⌷c r∧←100 'TIMEOUT' ''Assert c←#.DRC.Wait(2⊃c1)100 r∧←100 'TIMEOUT' ''Assert c←#.DRC.Wait(2⊃c2)100 r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c3)100 r∧←100 'TIMEOUT' ''Assert c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Close'C1' r∧←0 Assert⊃c←#.DRC.Close'C2' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c1)100 r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 r∧←0 Assert⊃c←#.DRC.Close'S1' Report r ∇ ∇ r←Connect(addr port srv prot);c;c1 r←1 r∧←0≡⊃c←#.DRC.Clt''addr port,(0<⍴prot)/(⊂'Protocol'prot) r∧←0 'Connect' 0≡(⊂1 3 4)⌷c1←4↑#.DRC.Wait srv 100 r∧←0≡⊃#.DRC.Close 2⊃c r∧←0 'Error' 1119≡(⊂1 3 4)⌷c1←4↑#.DRC.Wait(srv)100 ∇ ∇ r←TestGetAddrInfo;srvs;tests;res;rr;c r←1 srvs←('SA' '' 5000)('S4' '' 5004('Protocol' 'ipv4'))('S6' '' 5006('Protocol' 'ipv6')) r←∧/rr←{0(1⊃⍵)≡#.DRC.Srv ⍵}¨srvs :If ~r 'Failed: ',⍕rr/srvs :EndIf tests←('localhost' '127.0.0.1' '::1' '')∘.{(⊂⍺),⍵}{⍵[3 1]}¨srvs res←(⍴tests)⍴1 res[2;3]←0 res[3;2]←0 rr←Connect¨tests,¨⊂⊂'' r∧←res Assert rr r∧←((⍴srvs)⍴0)Assert⊃¨c←#.DRC.Close¨1⊃¨srvs Report r ∇ ∇ r←TestProtocol;srvs;tests;res;rr;c r←1 srvs←('SA' '' 5000)('S4' '' 5004('Protocol' 'ipv4'))('S6' '' 5006('Protocol' 'ipv6')) r←∧/rr←{0(1⊃⍵)≡#.DRC.Srv ⍵}¨srvs :If ~r 'Failed: ',⍕rr/srvs :EndIf tests←(('localhost'⍬)('localhost' 'ip')('localhost' 'ipv4')('localhost' 'ipv6'))∘.{(⍺,⍵)[1 3 4 2]}{⍵[3 1]}¨srvs res←(⍴tests)⍴1 res[3;3]←0 res[4;2]←0 rr←Connect¨tests r∧←res Assert rr r∧←((⍴srvs)⍴0)Assert⊃¨c←#.DRC.Close¨1⊃¨srvs Report r ∇ ∇ r←TestProgress;c;rs;cmd;rc r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'EventMode' 1 r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 r∧←0 'C1'Assert c←#.DRC.Clt'C1' '' 5000 r∧←0 Assert⊃c←#.DRC.Send'C1' 'testing 1 2 3' cmd←2⊃c r∧←0 'Connect'Assert(⊂1 3)⌷c←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'testing 1 2 3'Assert(⊂1 3 4)⌷rs←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('10%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('20%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('30%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('40%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('50%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('60%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('70%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('80%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('90%') r∧←0 'Progress' '10%'Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←0 'Progress' '20%'Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←0 'Progress' '30%'Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←0 'Progress' '40%'Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←0 Assert⊃c←#.DRC.Respond(2⊃rs)(⌽4⊃rs) ⎕DL 0.1 r∧←0 'Receive'(⌽'testing 1 2 3')Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←1010 Assert⊃rc←#.DRC.Wait cmd 100 r∧←0 Assert⊃#.DRC.Close'C1' r∧←0 'Closed' 1119 Assert(⊂1 3 4)⌷rs←#.DRC.Wait'S1' 100 r∧←0 'Timeout' 100 Assert(⊂1 3 4)⌷rs←#.DRC.Wait'S1' 100 r∧←0 Assert⊃#.DRC.Close'S1' Report r ∇ ∇ r←TestUDPSimple;c;addrs;rc;con2;con1;data;a;sock r←1 r∧←0 Assert⊃c←#.DRC.GetProp'.' 'Ipv4Addrs' addrs←(2⊃c)[;2] ⍝addrs←(¯2↓¨2⊃¨{('IPv4'∘≡∘⊃¨⍵)/⍵}2⊃c) r∧←0 'UdpS'Assert c←#.DRC.Srv'UdpS' '' 5000 'udp' 10000('Protocol' 'ipv4') r∧←0 Assert⊃c←#.DRC.Clt'UdpC' '127.0.0.1' 5000 'udp' 10000('Protocol' 'ipv4') con1←2⊃c r∧←0 Assert⊃c←#.DRC.Send con1'Testing Udp1' r∧←0 Assert⊃c←#.DRC.Send'UdpC'('127.0.0.1' 5000 'Testing Udp2') con2←2⊃c r∧←0 'Block'('Testing Udp1')Assert(⊂1 3 4)⌷rc←#.DRC.Wait'UdpS' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃rc)'Testing Udp1' r∧←0 'Block'('Testing Udp2')Assert(⊂1 3 4)⌷rc←#.DRC.Wait'UdpS' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃rc)'Testing Udp2' r∧←0 'Block'('Testing Udp1')Assert(⊂1 3 4)⌷rc←#.DRC.Wait con1 100 r∧←0 'Block'('Testing Udp2')Assert(⊂1 3 4)⌷rc←#.DRC.Wait con2 100 :For a :In addrs data←'Testing Udp ',a r∧←0 Assert⊃c←#.DRC.Send'UdpC'(a 5000 data) con2←2⊃c r∧←0 'Block'data Assert(⊂1 3 4)⌷rc←#.DRC.Wait'UdpS' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃rc)(⌽data) r∧←0 'Block'(⌽data)Assert(⊂1 3 4)⌷rc←#.DRC.Wait con2 100 :EndFor sock←⍬ :For a :In addrs data←'Testing Udp ',a r∧←0 Assert⊃c←#.DRC.Clt''a 5000 'udp' 10000('Protocol' 'ipv4') con2←2⊃c sock,←⊂{(¯1+⍵⍳'.')↑⍵}con2 r∧←0 Assert⊃c←#.DRC.Send con2 data r∧←0 'Block'data Assert(⊂1 3 4)⌷rc←#.DRC.Wait'UdpS' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃rc)(⌽data) r∧←0 'Block'(⌽data)Assert(⊂1 3 4)⌷rc←#.DRC.Wait con2 100 :EndFor :For n :In #.DRC.Names'.' 'Connection: ',n :For l :In #.DRC.Names n ' ',⍕decodeAddr l :EndFor :EndFor r∧←∧/0=⊃¨#.DRC.Close¨sock r∧←0 Assert⊃c←#.DRC.Close'UdpC' r∧←0 Assert⊃c←#.DRC.Close'UdpS' Report r ∇ ∇ r←TestWebSocket;c;port;wscon;len;data;c1;Features;nl;drt r←1 to83←{⍵+¯256×⍵>127} nl←⎕UCS 13 10 port←8088 Features←1 ⍝ Feature 0=APL negotiate 1=AutoUpgrade c←#.DRC.Srv'S1' ''port'http' 450000 r∧←0 'S1'Assert c :If r=1 r∧←0 Assert⊃c←#.DRC.SetProp'S1' 'WSFeatures'Features ⍝ Set feature for server applies to all incomming connections c←#.DRC.Clt'C1' 'localhost'port'http' 450000 r∧←0 'C1'Assert c :If r=1 r∧←0 Assert⊃c←#.DRC.SetProp'C1' 'WSFeatures'Features c←#.DRC.Wait'S1' 1000 r∧←0 'Connect'Assert c[1 3] ⍝ Client requests to upgrade the connection 4th arg is extra headers remember to add nl r∧←0 Assert⊃c←#.DRC.SetProp'C1' 'WSUpgrade'('/' 'localhost'('BHCHeader: Gil',nl)) c←#.DRC.Wait'S1' 1000 :If 0 'WSUpgrade'≡c[1 3] ⍝ Auto upgrade event 4⊃c is the Incomming request but connection have been upgraded r∧←1 :ElseIf 0 'WSUpgradeReq'≡c[1 3] ⍝ Negotiate inspect headers and accept request with the extra headers you need. :If 0<≢4⊃c r∧←0 Assert⊃c1←#.DRC.SetProp(2⊃c)'WSAccept'((4⊃c)('GILHeader: bhc',nl)) :EndIf :Else r←0 :EndIf wscon←2⊃c ⍝ test c←#.DRC.Wait'C1' 1000 ⍝ returns WSUpgrade and 4⊃c is the peers accept headers, WSResponce 4⊃c is the same but you have to accept the upgrade. :If 0 'WSResponce'≡c[1 3] r∧←0 Assert⊃c1←#.DRC.SetProp(2⊃c)'WSAccept'((4⊃c)'') :EndIf :For drt :In 80 160 320 :For len :In 0 10 124 125 126 127 128 65535 65536 70000 data←drt utf8 len ⍝ r∧←0 Assert⊃c←#.DRC.Send'C1'(data 1) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 1 1)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Send wscon(data 1) c←#.DRC.Wait'C1' 1000 r∧←0 'WSReceive'(data 1 1)Assert c[1 3 4] :EndFor :EndFor :For offset :In -⎕IO+0 128 :For len :In 0 10 124 125 126 127 128 65535 65536 70000 data←offset+len⍴⍳256 r∧←0 Assert⊃c←#.DRC.Send'C1'(data 1) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'((to83 data)1 2)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Send wscon(data 1) c←#.DRC.Wait'C1' 1000 r∧←0 'WSReceive'((to83 data)1 2)Assert c[1 3 4] :EndFor :EndFor :For drt :In 80 160 320 :For len :In 0 10 124 125 126 127 128 65535 65536 70000 data←drt utf8 len ⍝ Fin←len=70000 r∧←0 Assert⊃c←#.DRC.Send'C1'(data Fin) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data Fin 1)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Send wscon(data Fin) c←#.DRC.Wait'C1' 1000 r∧←0 'WSReceive'(data Fin 1)Assert c[1 3 4] :EndFor :EndFor :For offset :In -⎕IO+0 128 :For len :In 0 10 124 125 126 127 128 65535 65536 70000 data←offset+len⍴⍳256 Fin←len=70000 r∧←0 Assert⊃c←#.DRC.Send'C1'(data Fin) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'((to83 data)Fin 2)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Send wscon(data Fin) c←#.DRC.Wait'C1' 1000 r∧←0 'WSReceive'((to83 data)Fin 2)Assert c[1 3 4] :EndFor :EndFor ⍝ test wrong type data←80 utf8 1000 ⍝ r∧←0 Assert⊃c←#.DRC.Send'C1'(data 0) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 0 1)Assert c[1 3 4] data←(-128+⎕IO)+1000⍴⍳256 r∧←1004 Assert⊃c←#.DRC.Send'C1'(data 1) data←80 utf8 1000 ⍝ r∧←0 Assert⊃c←#.DRC.Send'C1'(data 1) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 1 1)Assert c[1 3 4] ⍝ test wrong type data←(-128+⎕IO)+1000⍴⍳256 r∧←0 Assert⊃c←#.DRC.Send'C1'(data 0) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 0 2)Assert c[1 3 4] data←80 utf8 1000 ⍝ r∧←1004 Assert⊃c←#.DRC.Send'C1'(data 1) data←(-128+⎕IO)+1000⍴⍳256 r∧←0 Assert⊃c←#.DRC.Send'C1'(data 1) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 1 2)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Close'C1' c←#.DRC.Wait'S1' 10000 r∧←0 'Error' 1119 Assert c[1 3 4] :EndIf r∧←0 Assert⊃c←#.DRC.Close'S1' :EndIf ∇ ∇ r←Run;c r←1 show←0 StopOnError←1 Errors←⍬ ⍝c←#.DRC.Init'' ⍝r∧←0=⊃c r∧←0 Assert⊃c←#.DRC.SetProp'.' 'EventMode' 0 ⍝ Close any extant connections c←#.DRC.Close¨#.DRC.Names'.' r∧←TestThreaded c←#.DRC.Close¨#.DRC.Names'.' r∧←TestSentCompleteCMD c←#.DRC.Close¨#.DRC.Names'.' r∧←TestSentCompleteText c←#.DRC.Close¨#.DRC.Names'.' r∧←TestEndpoints c←#.DRC.Close¨#.DRC.Names'.' r∧←TestSendFile c←#.DRC.Close¨#.DRC.Names'.' r∧←TestSendFileBlk c←#.DRC.Close¨#.DRC.Names'.' r∧←TestPause c←#.DRC.Close¨#.DRC.Names'.' r∧←TestGetAddrInfo c←#.DRC.Close¨#.DRC.Names'.' r∧←TestProtocol c←#.DRC.Close¨#.DRC.Names'.' r∧←TestRaw c←#.DRC.Close¨#.DRC.Names'.' r∧←TestWebSocket c←#.DRC.Close¨#.DRC.Names'.' r∧←TestReadyList2 4 8 1 0 c←#.DRC.Close¨#.DRC.Names'.' r∧←TestProgress :If 0<⍴Errors Errors :EndIf ∇ ∇ r←decodeAddr addr;parts parts←¯2↑'.:'{m←(⊃⍺),⍵ ⋄ 1↓¨(m∊⍺)⊂m}addr r←(base64 1⊃parts)(dec 2⊃parts) ∇ base64←{⎕IO ⎕ML←0 1 ⍝ Base64 encoding and decoding as used in MIME. chars←'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' bits←{,⍉(⍺⍴2)⊤⍵} ⍝ encode each element of ⍵ in ⍺ bits, ⍝ and catenate them all together part←{((⍴⍵)⍴⍺↑1)⊂⍵} ⍝ partition ⍵ into chunks of length ⍺ 0=2|⎕DR ⍵:2∘⊥∘(8∘↑)¨8 part{(-8|⍴⍵)↓⍵}6 bits{(⍵≠64)/⍵}chars⍳⍵ ⍝ decode a string into octets four←{ ⍝ use 4 characters to encode either 8=⍴⍵:'=='∇ ⍵,0 0 0 0 ⍝ 1, 16=⍴⍵:'='∇ ⍵,0 0 ⍝ 2 chars[2∘⊥¨6 part ⍵],⍺ ⍝ or 3 octets of input } cats←⊃∘(,/)∘((⊂'')∘,) ⍝ catenate zero or more strings cats''∘four¨24 part 8 bits ⍵ } dec←{⎕IO ⎕ML←0 1 ⍝ Decimal from hexadecimal ⍺←0 ⍝ unsigned by default. 1<⍴⍴⍵:↑⍺ ∇¨↓⍵ ⍝ vector-wise: 0=≢⍵:0 ⍝ dec'' → 0. 1≠≡,⍵:⍺ ∇¨⍵ ⍝ simple-array-wise: ' '=⊃⍵:⍺ ∇ 1↓⍵ ⍝ ignoring leading and ' '=⊃⌽⍵:⍺ ∇ ¯1↓⍵ ⍝ ... trailing blanks. ' '∊⍵:⍺ ∇¨{1↓¨(⍵=' ')⊂⍵}' ',⍵ ⍝ blank-separated: v←16|'0123456789abcdef0123456789ABCDEF'⍳⍵ ⍝ hex digits. 11::'Too big'⎕SIGNAL 11 ⍝ number too big. (16⊥v)-⍺×(8≤⊃v)×16*≢v ⍝ (signed) decimal number. } :EndNamespace ",16229,True,3503.796746738493,median "package com.company.assembleegameclient.objects { import com.company.assembleegameclient.map.Camera; import com.company.assembleegameclient.map.Square; import com.company.assembleegameclient.map.mapoverlay.CharacterStatusText; import com.company.assembleegameclient.objects.particles.HealingEffect; import com.company.assembleegameclient.objects.particles.LevelUpEffect; import com.company.assembleegameclient.parameters.Parameters; import com.company.assembleegameclient.parameters.Parameters; import com.company.assembleegameclient.sound.SoundEffectLibrary; import com.company.assembleegameclient.tutorial.Tutorial; import com.company.assembleegameclient.tutorial.doneAction; import com.company.assembleegameclient.util.AnimatedChar; import com.company.assembleegameclient.util.ConditionEffect; import com.company.assembleegameclient.util.FameUtil; import com.company.assembleegameclient.util.FreeList; import com.company.assembleegameclient.util.MaskedImage; import com.company.assembleegameclient.util.TextureRedrawer; import com.company.assembleegameclient.util.redrawers.GlowRedrawer; import com.company.util.CachingColorTransformer; import com.company.util.ConversionUtil; import com.company.util.GraphicsUtil; import com.company.util.IntPoint; import com.company.util.MoreColorUtil; import com.company.util.PointUtil; import com.company.util.Trig; import flash.display.BitmapData; import flash.display.GraphicsPath; import flash.display.GraphicsSolidFill; import flash.display.IGraphicsData; import flash.geom.ColorTransform; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Vector3D; import flash.utils.Dictionary; import flash.utils.getTimer; import kabam.rotmg.assets.services.CharacterFactory; import kabam.rotmg.chat.model.ChatMessage; import kabam.rotmg.constants.ActivationType; import kabam.rotmg.constants.GeneralConstants; import kabam.rotmg.constants.UseType; import kabam.rotmg.core.StaticInjectorContext; import kabam.rotmg.game.model.PotionInventoryModel; import kabam.rotmg.game.signals.AddTextLineSignal; import kabam.rotmg.game.view.components.QueuedStatusText; import kabam.rotmg.messaging.impl.data.StatData; import kabam.rotmg.stage3D.GraphicsFillExtra; import kabam.rotmg.text.model.NumberKey; import kabam.rotmg.text.model.TextKey; import kabam.rotmg.text.view.BitmapTextFactory; import kabam.rotmg.text.view.stringBuilder.LineBuilder; import kabam.rotmg.text.view.stringBuilder.StaticStringBuilder; import kabam.rotmg.text.view.stringBuilder.StringBuilder; import kabam.rotmg.ui.model.TabStripModel; import org.swiftsuspenders.Injector; public class Player extends Character { public static const MS_BETWEEN_TELEPORT:int = 10000; private static const MOVE_THRESHOLD:Number = 0.4; private static const NEARBY:Vector. = new [new Point(0, 0), new Point(1, 0), new Point(0, 1), new Point(1, 1)]; private static const RANK_OFFSET_MATRIX:Matrix = new Matrix(1, 0, 0, 1, 2, 2); private static const NAME_OFFSET_MATRIX:Matrix = new Matrix(1, 0, 0, 1, 20, 1); private static const MIN_MOVE_SPEED:Number = 0.004; private static const MAX_MOVE_SPEED:Number = 0.0096; private static const MIN_ATTACK_MULT:Number = 0.5; private static const MAX_ATTACK_MULT:Number = 2; private static const LOW_HEALTH_CT_OFFSET:int = 128; private static var lowHealthCT:Dictionary = new Dictionary(); public static var empiresCoin_:int = 0; public static var accountType_:int = 0; public static var isAdmin:Boolean = false; public static var isMod:Boolean = false; private static var newP:Point = new Point(); public var petObjectId:int = 0; public var petHpHealingAverageMin:int = 0; public var petHpHealingAverageMax:int = 0; public var petHpHealingAverageBonus:int = 0; public var petMpHealingAverageMin:int = 0; public var petMpHealingAverageMax:int = 0; public var petMpHealingAverageBonus:int = 0; public var petAttackCooldown:int = 0; public var petAttackChance:int = 0; public var petAttackDamageMin:int = 0; public var petAttackDamageMax:int = 0; public var isTrading:Boolean = false; public var xpTimer:int; public var skinId:int; public var skin:AnimatedChar; public var isShooting:Boolean; public var accountId_:String = """"; public var credits_:int = 0; public var tokens_:int = 0; public var numStars_:int = 0; public var fame_:int = 0; public var nameChosen_:Boolean = false; public var currFame_:int = 0; public var nextClassQuestFame_:int = -1; public var guildName_:String = null; public var guildRank_:int = -1; public var isFellowGuild_:Boolean = false; public var breath_:int = -1; public var maxMP_:int = 200; public var mp_:Number = 0; public var nextLevelExp_:int = 1000; public var exp_:int = 0; public var attack_:String = null; public var speed_:String = null; public var dexterity_:String = null; public var vitality_:String = null; public var wisdom_:String = null; public var maxHPBoost_:String = null; public var maxMPBoost_:String = null; public var attackBoost_:String = null; public var defenseBoost_:String = null; public var speedBoost_:String = null; public var vitalityBoost_:String = null; public var wisdomBoost_:String = null; public var dexterityBoost_:String = null; public var xpBoost_:int = 0; public var healthPotionCount_:int = 0; public var magicPotionCount_:int = 0; public var attackMax_:int = 0; public var defenseMax_:int = 0; public var speedMax_:int = 0; public var dexterityMax_:int = 0; public var vitalityMax_:int = 0; public var wisdomMax_:int = 0; public var maxHPMax_:int = 0; public var maxMPMax_:int = 0; public var hasBackpack_:Boolean = false; public var accountType_:int = 0; public var admin_:Boolean = false; public var starred_:Boolean = false; public var ignored_:Boolean = false; public var distSqFromThisPlayer_:Number = 0; protected var rotate_:Number = 0; protected var relMoveVec_:Point = null; protected var moveMultiplier_:Number = 1; public var attackPeriod_:Number = 0; public var attackAmount_:int = 0; public var isDazed_:Boolean = false; public var isBerserk_:Boolean = false; public var minAttackFrequency_:Number = 0; public var maxAttackFrequency_:Number = 0; public var weaponRateOfFire_:Number = 0; public var nextAltAttack_:int = 0; public var nextTeleportAt_:int = 0; public var dropBoost:int = 0; public var tierBoost:int = 0; protected var healingEffect_:HealingEffect = null; protected var nearestMerchant_:Merchant = null; public var isDefaultAnimatedChar:Boolean = true; public var projectileIdSetOverrideNew:String = """"; public var projectileIdSetOverrideOld:String = """"; private var addTextLine:AddTextLineSignal; private var factory:CharacterFactory; private var ip_:IntPoint; private var breathBackFill_:GraphicsSolidFill = null; private var breathBackPath_:GraphicsPath = null; private var breathFill_:GraphicsSolidFill = null; private var breathPath_:GraphicsPath = null; private var hallucinatingMaskedImage_:MaskedImage = null; private var slideVec_:Vector3D; public function Player(_arg1:XML) { this.minAttackFrequency_ = 0.0015; this.maxAttackFrequency_ = 0.008; this.ip_ = new IntPoint(); var _local2:Injector = StaticInjectorContext.getInjector(); this.addTextLine = _local2.getInstance(AddTextLineSignal); this.factory = _local2.getInstance(CharacterFactory); super(_arg1); this.attackMax_ = int(_arg1.Attack.@max); this.defenseMax_ = int(_arg1.Defense.@max); this.speedMax_ = int(_arg1.Speed.@max); this.dexterityMax_ = int(_arg1.Dexterity.@max); this.vitalityMax_ = int(_arg1.HpRegen.@max); this.wisdomMax_ = int(_arg1.MpRegen.@max); this.maxHPMax_ = int(_arg1.MaxHitPoints.@max); this.maxMPMax_ = int(_arg1.MaxMagicPoints.@max); texturingCache_ = new Dictionary(); this.slideVec_ = new Vector3D(); } public static function fromPlayerXML(name:String, playerXML:XML):Player { var _local3:int = int(playerXML.ObjectType); var _local4:XML = ObjectLibrary.xmlLibrary_[_local3]; var _local5:Player = new Player(_local4); _local5.name_ = name; _local5.level_ = int(playerXML.Level); _local5.exp_ = int(playerXML.Exp); _local5.equipment_ = ConversionUtil.toIntVector(playerXML.Equipment); _local5.calculateStatBoosts(); _local5.lockedSlot = new Vector.(_local5.equipment_.length); _local5.maxHP_ = (Parameters.parse(_local5.maxHPBoost_) + int(playerXML.MaxHitPoints)); _local5.hp_ = int(playerXML.HitPoints); _local5.maxMP_ = (Parameters.parse(_local5.maxMPBoost_) + int(playerXML.MaxMagicPoints)); _local5.mp_ = int(playerXML.MagicPoints); _local5.attack_ = (Parameters.parse(_local5.attackBoost_) + int(playerXML.Attack)).toString(); _local5.defense_ = (Parameters.parse(_local5.defenseBoost_) + int(playerXML.Defense)).toString(); _local5.speed_ = (Parameters.parse(_local5.speedBoost_) + int(playerXML.Speed)).toString(); _local5.dexterity_ = (Parameters.parse(_local5.vitalityBoost_) + int(playerXML.Dexterity)).toString(); _local5.vitality_ = (Parameters.parse(_local5.wisdomBoost_) + int(playerXML.HpRegen)).toString(); _local5.wisdom_ = (Parameters.parse(_local5.dexterityBoost_) + int(playerXML.MpRegen)).toString(); _local5.tex1Id_ = int(playerXML.Tex1); _local5.tex2Id_ = int(playerXML.Tex2); _local5.hasBackpack_ = int(playerXML.HasBackpack) != 0; return (_local5); } public function calculateStatBoosts():void { var _local2:int; var _local3:XML; var _local4:XML; var _local5:int; var _local6:int; this.maxHPBoost_ = ""0""; this.maxMPBoost_ = ""0""; this.attackBoost_ = ""0""; this.defenseBoost_ = ""0""; this.speedBoost_ = ""0""; this.vitalityBoost_ = ""0""; this.wisdomBoost_ = ""0""; this.dexterityBoost_ = ""0""; var _local1:uint; while (_local1 < GeneralConstants.NUM_EQUIPMENT_SLOTS) { if (((equipment_) && ((equipment_.length > _local1)))) { _local2 = equipment_[_local1]; if (_local2 != -1) { _local3 = ObjectLibrary.xmlLibrary_[_local2]; if (((!((_local3 == null))) && (_local3.hasOwnProperty(""ActivateOnEquip"")))) { for each (_local4 in _local3.ActivateOnEquip) { if (_local4.toString() == ""IncrementStat"") { _local5 = int(_local4.@stat); _local6 = int(_local4.@amount); switch (_local5) { case StatData.MAX_HP_STAT: this.maxHPBoost_ = (this.maxHPBoost_ + _local6); break; case StatData.MAX_MP_STAT: this.maxMPBoost_ = (this.maxMPBoost_ + _local6); break; case StatData.ATTACK_STAT: this.attackBoost_ = (Parameters.parse(this.attackBoost_) + _local6).toString(); break; case StatData.DEFENSE_STAT: this.defenseBoost_ = (Parameters.parse(this.defenseBoost_) + _local6).toString(); break; case StatData.SPEED_STAT: this.speedBoost_ = (Parameters.parse(this.speedBoost_) + _local6).toString(); break; case StatData.VITALITY_STAT: this.vitalityBoost_ = (Parameters.parse(this.vitalityBoost_) + _local6).toString(); break; case StatData.WISDOM_STAT: this.wisdomBoost_ = (Parameters.parse(this.wisdomBoost_) + _local6).toString(); break; case StatData.DEXTERITY_STAT: this.dexterityBoost_ = (Parameters.parse(this.dexterityBoost_) + _local6).toString(); break; } } } } } } _local1++; } } public function setRelativeMovement(_arg1:Number, _arg2:Number, _arg3:Number):void { var _local4:Number; if (this.relMoveVec_ == null) { this.relMoveVec_ = new Point(); } this.rotate_ = _arg1; this.relMoveVec_.x = _arg2; this.relMoveVec_.y = _arg3; if (isConfused()) { _local4 = this.relMoveVec_.x; this.relMoveVec_.x = -(this.relMoveVec_.y); this.relMoveVec_.y = -(_local4); this.rotate_ = -(this.rotate_); } } public function setCredits(_arg1:int):void { this.credits_ = _arg1; } public function setTokens(_arg1:int):void { this.tokens_ = _arg1; } public function setGuildName(_arg1:String):void { var _local3:GameObject; var _local4:Player; var _local5:Boolean; this.guildName_ = _arg1; var _local2:Player = map_.player_; if (_local2 == this) { for each (_local3 in map_.goDict_) { _local4 = (_local3 as Player); if (((!((_local4 == null))) && (!((_local4 == this))))) { _local4.setGuildName(_local4.guildName_); } } } else { _local5 = ((((((!((_local2 == null))) && (!((_local2.guildName_ == null))))) && (!((_local2.guildName_ == """"))))) && ((_local2.guildName_ == this.guildName_))); if (_local5 != this.isFellowGuild_) { this.isFellowGuild_ = _local5; nameBitmapData_ = null; } } } public function isTeleportEligible(_arg1:Player):Boolean { return (!(((_arg1.isPaused()) || (_arg1.isInvisible())))); } public function msUtilTeleport():int { var _local1:int = getTimer(); return (Math.max(0, (this.nextTeleportAt_ - _local1))); } public function teleportTo(_arg1:Player):Boolean { if (isPaused()) { this.addTextLine.dispatch(this.makeErrorMessage(TextKey.PLAYER_NOTELEPORTWHILEPAUSED)); return (false); } var _local2:int = this.msUtilTeleport(); if (_local2 > 0) { this.addTextLine.dispatch(this.makeErrorMessage(TextKey.PLAYER_TELEPORT_COOLDOWN, {""seconds"": int(((_local2 / 1000) + 1))})); return (false); } if (!this.isTeleportEligible(_arg1)) { if (_arg1.isInvisible()) { this.addTextLine.dispatch(this.makeErrorMessage(TextKey.TELEPORT_INVISIBLE_PLAYER, {""player"": _arg1.name_})); } else { this.addTextLine.dispatch(this.makeErrorMessage(TextKey.PLAYER_TELEPORT_TO_PLAYER, {""player"": _arg1.name_})); } return (false); } map_.gs_.gsc_.playerText(""/teleport "" + _arg1.name_); this.nextTeleportAt_ = (getTimer() + MS_BETWEEN_TELEPORT); return (true); } private function makeErrorMessage(_arg1:String, _arg2:Object = null):ChatMessage { return (ChatMessage.make(Parameters.ERROR_CHAT_NAME, _arg1, -1, -1, """", false, _arg2)); } public function levelUpEffect(_arg1:String, _arg2:Boolean = true):void { if (_arg2) { this.levelUpParticleEffect(); } var _local3:QueuedStatusText = new QueuedStatusText(this, new LineBuilder().setParams(_arg1), 0xFF00, 2000); map_.mapOverlay_.addQueuedText(_local3); } public function handleLevelUp(_arg1:Boolean):void { SoundEffectLibrary.play(""level_up""); if (_arg1) { this.levelUpEffect(TextKey.PLAYER_NEWCLASSUNLOCKED, false); this.levelUpEffect(TextKey.PLAYER_LEVELUP); } else { this.levelUpEffect(TextKey.PLAYER_LEVELUP); } } public function levelUpParticleEffect(_arg1:uint = 0xFF00FF00):void { map_.addObj(new LevelUpEffect(this, _arg1, 20), x_, y_); } public function handleExpUp(_arg1:int):void { if (level_ == 20) { return; } var _local2:CharacterStatusText = new CharacterStatusText(this, 0xFF00, 1000); _local2.setStringBuilder(new LineBuilder().setParams(TextKey.PLAYER_EXP, {""exp"": _arg1})); map_.mapOverlay_.addStatusText(_local2); } private function getNearbyMerchant():Merchant { var _local3:Point; var _local4:Merchant; var _local1:int = ((((x_ - int(x_))) > 0.5) ? 1 : -1); var _local2:int = ((((y_ - int(y_))) > 0.5) ? 1 : -1); for each (_local3 in NEARBY) { this.ip_.x_ = (x_ + (_local1 * _local3.x)); this.ip_.y_ = (y_ + (_local2 * _local3.y)); _local4 = map_.merchLookup_[this.ip_]; if (_local4 != null) { return ((((PointUtil.distanceSquaredXY(_local4.x_, _local4.y_, x_, y_) < 1)) ? _local4 : null)); } } return (null); } public function walkTo(_arg1:Number, _arg2:Number):Boolean { this.modifyMove(_arg1, _arg2, newP); return (this.moveTo(newP.x, newP.y)); } override public function moveTo(_arg1:Number, _arg2:Number):Boolean { var _local3:Boolean = super.moveTo(_arg1, _arg2); if (map_.gs_.evalIsNotInCombatMapArea()) { this.nearestMerchant_ = this.getNearbyMerchant(); } return (_local3); } public function modifyMove(_arg1:Number, _arg2:Number, _arg3:Point):void { if (((isParalyzed()) || (isPetrified()))) { _arg3.x = x_; _arg3.y = y_; return; } var _local4:Number = (_arg1 - x_); var _local5:Number = (_arg2 - y_); if ((((((((_local4 < MOVE_THRESHOLD)) && ((_local4 > -(MOVE_THRESHOLD))))) && ((_local5 < MOVE_THRESHOLD)))) && ((_local5 > -(MOVE_THRESHOLD))))) { this.modifyStep(_arg1, _arg2, _arg3); return; } var _local6:Number = (MOVE_THRESHOLD / Math.max(Math.abs(_local4), Math.abs(_local5))); var _local7:Number = 0; _arg3.x = x_; _arg3.y = y_; var _local8:Boolean; while (!(_local8)) { if ((_local7 + _local6) >= 1) { _local6 = (1 - _local7); _local8 = true; } this.modifyStep((_arg3.x + (_local4 * _local6)), (_arg3.y + (_local5 * _local6)), _arg3); _local7 = (_local7 + _local6); } } public function modifyStep(_arg1:Number, _arg2:Number, _arg3:Point):void { var _local6:Number; var _local7:Number; var _local4:Boolean = ((((((x_ % 0.5) == 0)) && (!((_arg1 == x_))))) || (!((int((x_ / 0.5)) == int((_arg1 / 0.5)))))); var _local5:Boolean = ((((((y_ % 0.5) == 0)) && (!((_arg2 == y_))))) || (!((int((y_ / 0.5)) == int((_arg2 / 0.5)))))); if (((((!(_local4)) && (!(_local5)))) || (this.isValidPosition(_arg1, _arg2)))) { _arg3.x = _arg1; _arg3.y = _arg2; return; } if (_local4) { _local6 = (((_arg1) > x_) ? (int((_arg1 * 2)) / 2) : (int((x_ * 2)) / 2)); if (int(_local6) > int(x_)) { _local6 = (_local6 - 0.01); } } if (_local5) { _local7 = (((_arg2) > y_) ? (int((_arg2 * 2)) / 2) : (int((y_ * 2)) / 2)); if (int(_local7) > int(y_)) { _local7 = (_local7 - 0.01); } } if (!_local4) { _arg3.x = _arg1; _arg3.y = _local7; if (((!((square_ == null))) && (!((square_.props_.slideAmount_ == 0))))) { this.resetMoveVector(false); } return; } if (!_local5) { _arg3.x = _local6; _arg3.y = _arg2; if (((!((square_ == null))) && (!((square_.props_.slideAmount_ == 0))))) { this.resetMoveVector(true); } return; } var _local8:Number = (((_arg1) > x_) ? (_arg1 - _local6) : (_local6 - _arg1)); var _local9:Number = (((_arg2) > y_) ? (_arg2 - _local7) : (_local7 - _arg2)); if (_local8 > _local9) { if (this.isValidPosition(_arg1, _local7)) { _arg3.x = _arg1; _arg3.y = _local7; return; } if (this.isValidPosition(_local6, _arg2)) { _arg3.x = _local6; _arg3.y = _arg2; return; } } else { if (this.isValidPosition(_local6, _arg2)) { _arg3.x = _local6; _arg3.y = _arg2; return; } if (this.isValidPosition(_arg1, _local7)) { _arg3.x = _arg1; _arg3.y = _local7; return; } } _arg3.x = _local6; _arg3.y = _local7; } private function resetMoveVector(_arg1:Boolean):void { moveVec_.scaleBy(-0.5); if (_arg1) { moveVec_.y = (moveVec_.y * -1); } else { moveVec_.x = (moveVec_.x * -1); } } public function isValidPosition(_arg1:Number, _arg2:Number):Boolean { var _local3:Square = map_.getSquare(_arg1, _arg2); if (((!((square_ == _local3))) && ((((_local3 == null)) || (!(_local3.isWalkable())))))) { return (false); } var _local4:Number = (_arg1 - int(_arg1)); var _local5:Number = (_arg2 - int(_arg2)); if (_local4 < 0.5) { if (this.isFullOccupy((_arg1 - 1), _arg2)) { return (false); } if (_local5 < 0.5) { if (((this.isFullOccupy(_arg1, (_arg2 - 1))) || (this.isFullOccupy((_arg1 - 1), (_arg2 - 1))))) { return (false); } } else { if (_local5 > 0.5) { if (((this.isFullOccupy(_arg1, (_arg2 + 1))) || (this.isFullOccupy((_arg1 - 1), (_arg2 + 1))))) { return (false); } } } } else { if (_local4 > 0.5) { if (this.isFullOccupy((_arg1 + 1), _arg2)) { return (false); } if (_local5 < 0.5) { if (((this.isFullOccupy(_arg1, (_arg2 - 1))) || (this.isFullOccupy((_arg1 + 1), (_arg2 - 1))))) { return (false); } } else { if (_local5 > 0.5) { if (((this.isFullOccupy(_arg1, (_arg2 + 1))) || (this.isFullOccupy((_arg1 + 1), (_arg2 + 1))))) { return (false); } } } } else { if (_local5 < 0.5) { if (this.isFullOccupy(_arg1, (_arg2 - 1))) { return (false); } } else { if (_local5 > 0.5) { if (this.isFullOccupy(_arg1, (_arg2 + 1))) { return (false); } } } } } return (true); } public function isFullOccupy(_arg1:Number, _arg2:Number):Boolean { var _local3:Square = map_.lookupSquare(_arg1, _arg2); return ((((((_local3 == null)) || ((_local3.tileType_ == 0xFF)))) || (((!((_local3.obj_ == null))) && (_local3.obj_.props_.fullOccupy_))))); } override public function update(currentTime:int, deltaMS:int):Boolean { if (this.tierBoost && !isPaused()) { this.tierBoost = this.tierBoost - deltaMS; if (this.tierBoost < 0) { this.tierBoost = 0; } } if (this.dropBoost && !isPaused()) { this.dropBoost = this.dropBoost - deltaMS; if (this.dropBoost < 0) { this.dropBoost = 0; } } if (this.xpTimer && !isPaused()) { this.xpTimer = this.xpTimer - deltaMS; if (this.xpTimer < 0) { this.xpTimer = 0; } } if (isHealing() && !isPaused()) { if (this.healingEffect_ == null) { this.healingEffect_ = new HealingEffect(this); map_.addObj(this.healingEffect_, x_, y_); } } else { if (this.healingEffect_ != null) { map_.removeObj(this.healingEffect_.objectId_); this.healingEffect_ = null; } } var angle:Number = Parameters.data_.cameraAngle; if (this.rotate_ != 0) { angle = angle + deltaMS * Parameters.PLAYER_ROTATE_SPEED * this.rotate_; Parameters.data_.cameraAngle = angle; } if (map_.player_ == this && isPaused()) { return true; } if (this.relMoveVec_ != null) { if (this.relMoveVec_.x != 0 || this.relMoveVec_.y != 0) { var mvSpd:Number = this.getMoveSpeed(); var mvAngle:Number = Math.atan2(this.relMoveVec_.y, this.relMoveVec_.x); if (square_.props_.slideAmount_ > 0) { slideVec_.x = mvSpd * Math.cos(angle + mvAngle); slideVec_.y = mvSpd * Math.sin(angle + mvAngle); slideVec_.z = 0; moveVec_.scaleBy(square_.props_.slideAmount_); if (moveVec_.length < slideVec_.length) { slideVec_.scaleBy(1 - square_.props_.slideAmount_); moveVec_ = moveVec_.add(slideVec_); } } else { moveVec_.x = mvSpd * Math.cos(angle + mvAngle); moveVec_.y = mvSpd * Math.sin(angle + mvAngle); } } else { if (moveVec_.length > 0.00012 && square_.props_.slideAmount_ > 0) { moveVec_.scaleBy(square_.props_.slideAmount_); } else { moveVec_.x = 0; moveVec_.y = 0; } } if (square_ != null && square_.props_.push_) { moveVec_.x = moveVec_.x - square_.props_.animate_.dx_ / 1000; moveVec_.y = moveVec_.y - square_.props_.animate_.dy_ / 1000; } this.walkTo(x_ + deltaMS * moveVec_.x, y_ + deltaMS * moveVec_.y); } else { if (!super.update(currentTime, deltaMS)) { return false; } } if (map_.player_ == this && square_.props_.maxDamage_ > 0 && (square_.lastDamage_ + 500) < currentTime && !isInvincible() && (square_.obj_ == null || !square_.obj_.props_.protectFromGroundDamage_)) { var dmg:int = map_.gs_.gsc_.getNextDamage(square_.props_.minDamage_, square_.props_.maxDamage_); var conditionEffects:Vector. = new Vector.(); conditionEffects.push(ConditionEffect.GROUND_DAMAGE); damage(-1, dmg, conditionEffects, hp_ <= dmg, null); map_.gs_.gsc_.groundDamage(currentTime, x_, y_); square_.lastDamage_ = currentTime; } return true; } public function onMove():void { if (map_ == null) { return; } var _local1:Square = map_.getSquare(x_, y_); if (_local1.props_.sinking_) { sinkLevel_ = Math.min((sinkLevel_ + 1), Parameters.MAX_SINK_LEVEL); this.moveMultiplier_ = (0.1 + ((1 - (sinkLevel_ / Parameters.MAX_SINK_LEVEL)) * (_local1.props_.speed_ - 0.1))); } else { sinkLevel_ = 0; this.moveMultiplier_ = _local1.props_.speed_; } } override protected function makeNameBitmapData():BitmapData { var _local1:StringBuilder = new StaticStringBuilder(name_); var _local2:BitmapTextFactory = StaticInjectorContext.getInjector().getInstance(BitmapTextFactory); var _local3:BitmapData = _local2.make(_local1, 16, this.getNameColor(), true, NAME_OFFSET_MATRIX, true); _local3.draw(FameUtil.numStarsToIcon(this.numStars_), RANK_OFFSET_MATRIX); return (_local3); } private function getNameColor():uint { if (this.isFellowGuild_) { return (Parameters.FELLOW_GUILD_COLOR); } if (this.nameChosen_) { return (Parameters.NAME_CHOSEN_COLOR); } return (0xFFFFFF); } protected function drawBreathBar(_arg1:Vector., _arg2:int):void { var _local7:Number; var _local8:Number; if (this.breathPath_ == null) { this.breathBackFill_ = new GraphicsSolidFill(); this.breathBackPath_ = new GraphicsPath(GraphicsUtil.QUAD_COMMANDS, new Vector.()); this.breathFill_ = new GraphicsSolidFill(2542335); this.breathPath_ = new GraphicsPath(GraphicsUtil.QUAD_COMMANDS, new Vector.()); } if (this.breath_ <= Parameters.BREATH_THRESH) { _local7 = ((Parameters.BREATH_THRESH - this.breath_) / Parameters.BREATH_THRESH); this.breathBackFill_.color = MoreColorUtil.lerpColor(0x545454, 0xFF0000, (Math.abs(Math.sin((_arg2 / 300))) * _local7)); } else { this.breathBackFill_.color = 0x545454; } var _local3:int = 20; var _local4:int = 8; var _local5:int = 6; var _local6:Vector. = (this.breathBackPath_.data as Vector.); _local6.length = 0; _local6.push((posS_[0] - _local3), (posS_[1] + _local4), (posS_[0] + _local3), (posS_[1] + _local4), (posS_[0] + _local3), ((posS_[1] + _local4) + _local5), (posS_[0] - _local3), ((posS_[1] + _local4) + _local5)); _arg1.push(this.breathBackFill_); _arg1.push(this.breathBackPath_); _arg1.push(GraphicsUtil.END_FILL); if (this.breath_ > 0) { _local8 = (((this.breath_ / 100) * 2) * _local3); this.breathPath_.data.length = 0; _local6 = (this.breathPath_.data as Vector.); _local6.length = 0; _local6.push((posS_[0] - _local3), (posS_[1] + _local4), ((posS_[0] - _local3) + _local8), (posS_[1] + _local4), ((posS_[0] - _local3) + _local8), ((posS_[1] + _local4) + _local5), (posS_[0] - _local3), ((posS_[1] + _local4) + _local5)); _arg1.push(this.breathFill_); _arg1.push(this.breathPath_); _arg1.push(GraphicsUtil.END_FILL); } GraphicsFillExtra.setSoftwareDrawSolid(this.breathFill_, true); GraphicsFillExtra.setSoftwareDrawSolid(this.breathBackFill_, true); } override public function draw(_arg1:Vector., _arg2:Camera, _arg3:int):void { super.draw(_arg1, _arg2, _arg3); if (this != map_.player_) { if (!Parameters.screenShotMode_) { drawName(_arg1, _arg2); } } else { if (this.breath_ >= 0) { this.drawBreathBar(_arg1, _arg3); } } } private function getMoveSpeed():Number { if (isSlowed()) { return ((MIN_MOVE_SPEED * this.moveMultiplier_)); } var _local1:Number = (MIN_MOVE_SPEED + ((Parameters.parse(this.speed_) / 75) * (MAX_MOVE_SPEED - MIN_MOVE_SPEED))); if (((isSpeedy()) || (isNinjaSpeedy()))) { _local1 = (_local1 * 1.5); } return ((_local1 * this.moveMultiplier_)); } public function attackFrequency():Number { this.isDazed_ = isDazed(); this.isBerserk_ = isBerserk(); if (this.isDazed_) return this.minAttackFrequency_; var _rateOfFire:Number = this.minAttackFrequency_ + ((Parameters.parse(this.dexterity_) / 75) * (this.maxAttackFrequency_ - this.minAttackFrequency_)); if (this.isBerserk_) _rateOfFire *= 1.5; return (_rateOfFire); } private function attackMultiplier():Number { if (isWeak()) { return (MIN_ATTACK_MULT); } var _local1:Number = (MIN_ATTACK_MULT + ((Parameters.parse(this.attack_) / 75) * (MAX_ATTACK_MULT - MIN_ATTACK_MULT))); if (isDamaging()) { _local1 = (_local1 * 1.5); } return (_local1); } private function makeSkinTexture():void { var _local1:MaskedImage = this.skin.imageFromAngle(0, AnimatedChar.STAND, 0); animatedChar_ = this.skin; texture_ = _local1.image_; mask_ = _local1.mask_; this.isDefaultAnimatedChar = true; } private function setToRandomAnimatedCharacter():void { var _local1:Vector. = ObjectLibrary.hexTransforms_; var _local2:uint = Math.floor((Math.random() * _local1.length)); var _local3:int = _local1[_local2].@type; var _local4:TextureData = ObjectLibrary.typeToTextureData_[_local3]; texture_ = _local4.texture_; mask_ = _local4.mask_; animatedChar_ = _local4.animatedChar_; this.isDefaultAnimatedChar = false; } override protected function getTexture(camera:Camera, currentTime:int):BitmapData { var pos:Number = 0; var action:int = AnimatedChar.STAND; if (this.isShooting || currentTime < (attackStart_ + this.attackPeriod_)) { facing_ = attackAngle_; pos = ((currentTime - attackStart_) % this.attackPeriod_) / this.attackPeriod_; action = AnimatedChar.ATTACK; } else { if (moveVec_.x != 0 || moveVec_.y != 0) { var movPeriod:int = 3.5 / this.getMoveSpeed(); if (moveVec_.y != 0 || moveVec_.x != 0) { facing_ = Math.atan2(moveVec_.y, moveVec_.x); } pos = (currentTime % movPeriod) / movPeriod; action = AnimatedChar.WALK; } } if (this.isHexed()) { this.isDefaultAnimatedChar && this.setToRandomAnimatedCharacter(); } else { if (!this.isDefaultAnimatedChar) { this.makeSkinTexture(); } } var maskImg:MaskedImage; if (camera.isHallucinating_) { maskImg = getHallucinatingMaskedImage(); } else { maskImg = animatedChar_.imageFromFacing(facing_, camera, action, pos); } var tex1Id:int = tex1Id_; var tex2Id:int = tex2Id_; var tex:BitmapData; if (this.nearestMerchant_) { var merchDict:Dictionary = texturingCache_[this.nearestMerchant_]; if (merchDict == null) { texturingCache_[this.nearestMerchant_] = new Dictionary(); } else { tex = merchDict[maskImg]; } tex1Id = this.nearestMerchant_.getTex1Id(tex1Id_); tex2Id = this.nearestMerchant_.getTex2Id(tex2Id_); } else { tex = texturingCache_[maskImg]; } if (tex == null) { tex = TextureRedrawer.resize(maskImg.image_, maskImg.mask_, size_, false, tex1Id, tex2Id); if (this.nearestMerchant_ != null) { texturingCache_[this.nearestMerchant_][maskImg] = tex; } else { texturingCache_[maskImg] = tex; } } if (hp_ < maxHP_ * 0.2) { var intensity:Number = int(Math.abs(Math.sin(currentTime / 200)) * 10) / 10; var ct:ColorTransform = lowHealthCT[intensity]; if (ct == null) { ct = new ColorTransform(1, 1, 1, 1, intensity * LOW_HEALTH_CT_OFFSET, -intensity * LOW_HEALTH_CT_OFFSET, -intensity * LOW_HEALTH_CT_OFFSET); lowHealthCT[intensity] = ct; } tex = CachingColorTransformer.transformBitmapData(tex, ct); } var plrTex:BitmapData = texturingCache_[tex]; if (plrTex == null) { plrTex = GlowRedrawer.outlineGlow(tex, this.glowColor_); texturingCache_[tex] = plrTex; } if (isPaused() || isStasis() || isPetrified()) { plrTex = CachingColorTransformer.filterBitmapData(plrTex, PAUSED_FILTER); } else { if (isInvisible()) { plrTex = CachingColorTransformer.alphaBitmapData(plrTex, 40); } } return plrTex; } private function getHallucinatingMaskedImage():MaskedImage { if (hallucinatingMaskedImage_ == null) { hallucinatingMaskedImage_ = new MaskedImage(getHallucinatingTexture(), null); } return hallucinatingMaskedImage_; } override public function getPortrait():BitmapData { var _local1:MaskedImage; var _local2:int; if (portrait_ == null) { _local1 = animatedChar_.imageFromDir(AnimatedChar.RIGHT, AnimatedChar.STAND, 0); _local2 = ((4 / _local1.image_.width) * 100); portrait_ = TextureRedrawer.resize(_local1.image_, _local1.mask_, _local2, true, tex1Id_, tex2Id_); portrait_ = GlowRedrawer.outlineGlow(portrait_, 0); } return (portrait_); } public function useAltWeapon(_arg1:Number, _arg2:Number, _arg3:int):Boolean { var _local7:XML; var _local8:int; var _local9:Number; var _local10:int; var _local11:int; if ((((map_ == null)) || (isPaused()))) { return (false); } var _local4:int = equipment_[1]; if (_local4 == -1) { return (false); } var _local5:XML = ObjectLibrary.xmlLibrary_[_local4]; if ((((_local5 == null)) || (!(_local5.hasOwnProperty(""Usable""))))) { return (false); } var _local6:Point = map_.pSTopW(_arg1, _arg2); if (_local6 == null) { SoundEffectLibrary.play(""error""); return (false); } for each (_local7 in _local5.Activate) { if (_local7.toString() == ActivationType.TELEPORT) { if (!this.isValidPosition(_local6.x, _local6.y)) { SoundEffectLibrary.play(""error""); return (false); } } } _local8 = getTimer(); if (_arg3 == UseType.START_USE) { if (_local8 < this.nextAltAttack_) { SoundEffectLibrary.play(""error""); return (false); } _local10 = int(_local5.MpCost); if (_local10 > this.mp_) { SoundEffectLibrary.play(""no_mana""); return (false); } _local11 = 500; if (_local5.hasOwnProperty(TextKey.COOLDOWN)) { _local11 = (Number(_local5.Cooldown) * NumberKey.COOLDOWNVALUE); } this.nextAltAttack_ = (_local8 + _local11); map_.gs_.gsc_.useItem(_local8, objectId_, 1, _local4, _local6.x, _local6.y, _arg3, isTrading); if (_local5.Activate == ActivationType.SHOOT) { _local9 = Math.atan2(_arg2, _arg1); this.doShoot(_local4, _local5, (Parameters.data_.cameraAngle + _local9), false); } } else { if (_local5.hasOwnProperty(""MultiPhase"")) { map_.gs_.gsc_.useItem(_local8, objectId_, 1, _local4, _local6.x, _local6.y, _arg3, isTrading); _local10 = int(_local5.MpEndCost); if (_local10 <= this.mp_) { _local9 = Math.atan2(_arg2, _arg1); this.doShoot(_local4, _local5, (Parameters.data_.cameraAngle + _local9), false); } } } return (true); } public function attemptAttackAngle(_arg1:Number):void { this.shoot((Parameters.data_.cameraAngle + _arg1)); } override public function setAttack(_arg1:int, _arg2:Number):void { var _local3:XML = ObjectLibrary.xmlLibrary_[_arg1]; if ((((_local3 == null)) || (!(_local3.hasOwnProperty(TextKey.RATEOFFIRE))))) { return; } var _local4:Number = Number(_local3.RateOfFire); this.attackPeriod_ = ((NumberKey.RATEOFFIREVALUE / this.attackFrequency()) * (NumberKey.RATEOFFIREVALUE / _local4)); super.setAttack(_arg1, _arg2); } private function shoot(angle:Number):void { if (map_ == null || isStunned() || isPaused() || isPetrified()) return; var weapType:int = this.equipment_[0]; if (weapType == -1) return; var weapon:XML = ObjectLibrary.xmlLibrary_[weapType]; var curTime:int = getTimer(); this.weaponRateOfFire_ = Number(weapon.RateOfFire); this.attackPeriod_ = (NumberKey.RATEOFFIREVALUE / this.attackFrequency()) * (NumberKey.RATEOFFIREVALUE / this.weaponRateOfFire_); if (curTime < this.attackStart_ + this.attackPeriod_) return; doneAction(map_.gs_, Tutorial.ATTACK_ACTION); this.attackAngle_ = angle; this.attackStart_ = curTime; this.doShoot(weapType, weapon, attackAngle_, true); } private function doShoot(weaponType:int, weaponXML:XML, attackAngle:Number, isShooting:Boolean):void { var _local11:uint; var _local12:Projectile; var _local13:int; var _local14:int; var _local15:Number; var _local16:int; var arcGap:Number = (weaponXML.hasOwnProperty(TextKey.ARCGAP) ? Number(weaponXML.ArcGap) : NumberKey.ARCGAPVALUE) * Trig.toRadians; var _local8:Number = (arcGap * (this.attackAmount_ - 1)); var _local9:Number = (attackAngle - (_local8 / 2)); this.isShooting = isShooting; this.attackAmount_ = weaponXML.hasOwnProperty(TextKey.NUMPROJECTILES) ? int(weaponXML.NumProjectiles) : NumberKey.NUMPROJECTILESVALUE; var _local10:int; while (_local10 < this.attackAmount_) { _local11 = getBulletId(); _local12 = (FreeList.newObject(Projectile) as Projectile); if (((isShooting) && (!((this.projectileIdSetOverrideNew == """"))))) { _local12.reset(weaponType, 0, objectId_, _local11, _local9, this.attackStart_, this.projectileIdSetOverrideNew, this.projectileIdSetOverrideOld); } else { _local12.reset(weaponType, 0, objectId_, _local11, _local9, this.attackStart_); } _local13 = int(_local12.projProps_.minDamage_); _local14 = int(_local12.projProps_.maxDamage_); _local15 = ((isShooting) ? this.attackMultiplier() : 1); _local16 = (map_.gs_.gsc_.getNextDamage(_local13, _local14) * _local15); if (this.attackStart_ > (map_.gs_.moveRecords_.lastClearTime_ + 600)) { _local16 = 0; } _local12.setDamage(_local16); if ((((_local10 == 0)) && (!((_local12.sound_ == null))))) { SoundEffectLibrary.play(_local12.sound_, 0.75, false); } map_.addObj(_local12, (x_ + (Math.cos(attackAngle) * 0.3)), (y_ + (Math.sin(attackAngle) * 0.3))); map_.gs_.gsc_.playerShoot(_local12, this.attackAmount_, this.isDazed_, this.isBerserk_, this.minAttackFrequency_, this.maxAttackFrequency_, this.weaponRateOfFire_); _local9 = (_local9 + arcGap); _local10++; } } public function isHexed():Boolean { return (!(((condition_[ConditionEffect.CE_FIRST_BATCH] & ConditionEffect.HEXED_BIT) == 0))); } public function isInventoryFull():Boolean { if (equipment_ == null) { return (false); } var _local1:int = equipment_.length; var _local2:uint = 4; while (_local2 < _local1) { if (equipment_[_local2] <= 0) { return (false); } _local2++; } return (true); } public function nextAvailableInventorySlot():int { var _local1:int = ((this.hasBackpack_) ? equipment_.length : (equipment_.length - GeneralConstants.NUM_INVENTORY_SLOTS)); var _local2:uint = 4; while (_local2 < _local1) { if (equipment_[_local2] <= 0) { return (_local2); } _local2++; } return (-1); } public function numberOfAvailableSlots():int { var _local1:int = ((this.hasBackpack_) ? equipment_.length : (equipment_.length - GeneralConstants.NUM_INVENTORY_SLOTS)); var _local2:int; var _local3:uint = 4; while (_local3 < _local1) { if (equipment_[_local3] <= 0) { _local2++; } _local3++; } return (_local2); } public function swapInventoryIndex(_arg1:String):int { var _local2:int; var _local3:int; if (!this.hasBackpack_) { return (-1); } if (_arg1 == TabStripModel.BACKPACK) { _local2 = GeneralConstants.NUM_EQUIPMENT_SLOTS; _local3 = (GeneralConstants.NUM_EQUIPMENT_SLOTS + GeneralConstants.NUM_INVENTORY_SLOTS); } else { _local2 = (GeneralConstants.NUM_EQUIPMENT_SLOTS + GeneralConstants.NUM_INVENTORY_SLOTS); _local3 = equipment_.length; } var _local4:uint = _local2; while (_local4 < _local3) { if (equipment_[_local4] <= 0) { return (_local4); } _local4++; } return (-1); } public function getPotionCount(_arg1:int):int { switch (_arg1) { case PotionInventoryModel.HEALTH_POTION_ID: return (this.healthPotionCount_); case PotionInventoryModel.MAGIC_POTION_ID: return (this.magicPotionCount_); } return (0); } public function getTex1():int { return (tex1Id_); } public function getTex2():int { return (tex2Id_); } } } ",12159,False,2146.401397486322,median ":Namespace TestAllv3 (⎕IO ⎕ML ⎕WX)←1 0 3 StopOnError←0 show←0 ⍝ here be dragons Report←{⍵≠1: 'Failed: ',(2⊃⎕xsi),'[',(⍕2⊃⎕lc),']'⋄ } Assert←{⍺≡⍵:1 ⋄ Error 'Failed: ',(2⊃⎕xsi),'[',(⍕2⊃⎕lc),']' } ∇ r←Error arg :If show ⎕←arg :EndIf Errors,←⊂arg arg ⎕SIGNAL StopOnError/11 r←0 ∇ ∇ Log arg :If show ⎕←arg :EndIf ∇ ∇ At s ⎕DL 60|(s-6⊃⎕TS) ⎕TS ∇ ∇ r←apltype utf8 len;b;us;d r←'' b←127 2047 65535 2097151 67108863 2147483647 us←1 2 3 4 5 6 d←1 2 2 4 4 4 :Select apltype :Case 80 r←⎕UCS len↑(,⍉0 1∘.+1↑b),?len⍴255 :Case 160 r←⎕UCS len↑(,⍉0 1∘.+2↑b),(3⊃b),?len⍴65535 :Case 320 ⍝r←320 ⎕dr len↑ (,⍉0 1 ∘.+5↑b),(6⊃b) , ?len⍴2147483647 r←⎕UCS len↑(,⍉0 1∘.+3↑b),1114111,?len⍴1114111 :Else ⎕SIGNAL 11 :EndSelect ∇ ∇ MakeFile(name size data);nopen;tie nopen←{ ⍝ handle on null file. 0::⎕SIGNAL ⎕EN ⍝ signal error to caller. 22::⍵ ⎕NCREATE 0 ⍝ ~exists: create. ⍵ ⎕NTIE 0 ⍝ exists: tie. } tie←nopen name 0 ⎕NRESIZE tie (size⍴data)⎕NAPPEND tie ⎕NUNTIE tie ∇ ∇ cp←CertPath;instpath instpath←2 ⎕NQ'.' 'GetEnvironment' 'DYALOG' cp←instpath,'/TestCertificates/' ∇ ∇ cert←ReadCert relfilename;fn fn←CertPath,relfilename cert←⊃#.DRCShared.X509Cert.ReadCertFromFile fn,'-cert.pem' cert.KeyOrigin←'DER' (fn,'-key.pem') ∇ ∇ r←name DisplayCert z;dc;nc ⍝ Display information about a certificate dc←{,[1.5](2⊃⍵)[1 2 3 4 5 6]} nc←,[1.5]name'Version' 'SerialNo' 'Subject' 'Issuer' 'ValidFrom' 'ValidTo' dc←{⍵.(Formatted.(Version SerialNo Subject Issuer),Elements.(ValidFrom ValidTo))} :If 0=1⊃z :AndIf 0<⊃⍴2⊃z r←nc,' '⍪⍉↑dc¨2⊃z :Else ⋄ r←('Unable to retrieve ',name)z :EndIf ∇ ∇ r←TestSimple(prot secure);srvx509;cltx509;Port;c;Host;srv;clt;DefaultWaitTime;rs;con;srvcert;cltcert;pa;la r←1 Port←5000 Host←'localhost' srv←'S1' clt←'C1' DefaultWaitTime←5000 Cert←{(⍺.Cert)⍺⍺ ⍵.Cert} r∧←0 Assert⊃c←#.DRC.SetProp'.' 'EventMode' 0 :If secure srvx509←ReadCert'server/localhost' cltx509←ReadCert'client/client' r∧←0 Assert⊃c←#.DRC.SetProp'.' 'RootCertDir'(CertPath,'ca') :else srvx509←cltx509←⍬ :EndIf r∧←0 srv Assert c←#.DRC.Srv srv''Port,((prot≢'')/⊂('Protocol'prot)),secure/('X509'srvx509)('SSLValidation'(64)) r∧←0 clt Assert c←#.DRC.Clt clt Host Port,((prot≢'')/⊂('Protocol'prot)),secure/('x509'cltx509)('SSLValidation'(0)) r∧←0 Assert⊃c←#.DRC.Send clt'Request1' r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷rs←#.DRC.Wait srv DefaultWaitTime con←2⊃rs :If secure Log'Server Certificate'DisplayCert srvcert←#.DRC.GetProp clt'PeerCert' Log'Client Certificate'DisplayCert cltcert←#.DRC.GetProp con'PeerCert' r∧←(2 1⊃srvcert)Assert Cert 2 1⊃#.DRC.GetProp con'OwnCert' r∧←(2 1⊃cltcert)Assert Cert 2 1⊃#.DRC.GetProp clt'OwnCert' :EndIf r∧←0 'Receive' 'Request1'Assert(⊂1 3 4)⌷rs←#.DRC.Wait srv DefaultWaitTime r∧←0 Assert⊃c←#.DRC.Respond(2⊃rs)(⌽4⊃rs) r∧←0 'Receive'(⌽'Request1')Assert(⊂1 3 4)⌷rs←#.DRC.Wait clt DefaultWaitTime r∧←0 Assert⊃pa←#.DRC.GetProp clt'PeerAddr' r∧←0 Assert⊃la←#.DRC.GetProp con'LocalAddr' r∧←(2 2⊃la)Assert 2 2⊃pa r∧←0 Assert⊃la←#.DRC.GetProp clt'LocalAddr' r∧←0 Assert⊃pa←#.DRC.GetProp con'PeerAddr' r∧←(2 2⊃la)Assert 2 2⊃pa r∧←0 Assert⊃c←#.DRC.Close clt r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷rs←#.DRC.Wait srv DefaultWaitTime r∧←(,⊂srv) Assert #.DRC.Names'.' r∧←0 Assert⊃c←#.DRC.Close srv ∇ ∇ r←TestRaw;port;data;size;rs;c1;type;mode;c port←5000 to83←{⍵-256×⍵>127} r←1 :For mode :In 'Raw' 'Blkraw' r∧←0 'S1'Assert c←#.DRC.Srv'S1' ''port mode(40+2*21) r∧←0 'C1'Assert c←#.DRC.Clt'C1' 'localhost'port mode(40+2*21) r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c1←#.DRC.Wait'S1' 5000 :For type :In 83 163 :For size :In ,(2*1+⍳20)∘.+¯1 0 1 data←(-⎕IO)+size⍴⍳256 r∧←0 Assert 1⊃c←#.DRC.Send'C1'(type{⍺=83:to83 ⍵ ⋄ ⍵}data) rs←0 :While (rs S1 CON00000000 X00000000 cnx←{cons[;1]⍳('.'names ⍵)[2]} ⍝ order←1 last←0 :If (0 name)Assert c←#.DRC.Srv name''port :If ready 0=⊃c←#.DRC.SetProp name'ReadyList' 1 :EndIf :While 1 c←#.DRC.Waitt name 10000 :Select 1⊃c :Case 0 :Select 3⊃c :Case 'Error' ix←cnx 2⊃c :If 1119=4⊃c cons[ix;3]←0 :Else cons[ix;3]←4⊃c Log'Server ',(2⊃c),' Error ',⍕3⊃c :EndIf :Case 'Receive' ix←cnx 2⊃c order←last≤5 2⊃c last←5 2⊃c Log'Server received ',(2⊃c) :If 'Control'≡3⊃'.'names 2⊃c c1←#.DRC.Respond(2⊃c)(Control c) :Else c1←#.DRC.Respond(2⊃c)(⌽4⊃c) :EndIf :If 0=⊃c1 cons[ix;2]+←1 :Else Log'Server Respond failed ',c1 :EndIf :Case 'Connect' :If (ix←cnx 2⊃c)>⊃⍴cons cons⍪←(2⊃('.'names 2⊃c))1 ¯1 Log'Server New connection ',(2⊃c) :Else Log'Server same connection ',(2⊃c) :EndIf :EndSelect :Case 100 Log'Server timeout' :Continue :Case 1010 Log Control 4⍴⊂'STAT' :Leave :Else c r←0 :Leave :EndSelect :EndWhile :Else c r←0 :EndIf ∇ ∇ ServerThread(name n m ready);c;cons;cmds;names;cnx;cmx;order;last;ix;c1;r r←1 cons←(0 2)⍴0 cmds←n m⍴0 names←{1↓¨(⍺=⍺,⍵)⊂⍺,⍵} ⍝ 'S1.CON00000000.X00000000 => S1 CON00000000 X00000000 cnx←{cons[;1]⍳('.'names ⍵)[2]} ⍝ cmx←{⍎¯8↑3⊃'.'names ⍵} order←1 last←0 :If 0 'S1'Assert c←#.DRC.Srv name'' 5000 :If ready r∧←0=⊃c←#.DRC.SetProp name'ReadyList' 1 :EndIf :While 1 c←#.DRC.Waitt name 10000 :Select 1⊃c :Case 0 :Select 3⊃c :Case 'Error' ix←cnx 2⊃c :If 1119=4⊃c cons[ix;2]+←1 :Else cons[ix;2]+←100 Log'Server ',(2⊃c),' Error ',⍕3⊃c :EndIf :Case 'Receive' ix←cnx 2⊃c order←last≤5 2⊃c last←5 2⊃c Log'Server received ',(2⊃c) c1←#.DRC.Respond(2⊃c)(⌽4⊃c) :If 0=⊃c cons[ix;2]+←1 cmds[ix;cmx 2⊃c]+←1 :Else ∘∘∘ :EndIf :Case 'Connect' :If (ix←cnx 2⊃c)>⊃⍴cons cons⍪←(2⊃('.'names 2⊃c))1 Log'Server New connection ',(2⊃c) :Else cons[ix;2]+←100 Log'Server same connection ',(2⊃c) :EndIf :EndSelect :Case 100 Log'Server timeout' :Continue :Case 1010 :If ~res,←0=+/(cons[;2]≠2+m) (cons[;2]≠2+m)/cons[;1] :EndIf :If ~res,←∧/∧/cmds +/cmds≠1 :EndIf :If ~res,←order 'Out of order' :EndIf :Leave :Else c r←0 :Leave :EndSelect :EndWhile :Else c r←0 :EndIf ∇ ∇ r←CmdWait cmd;c r←0 waitfor←{100=1⊃cw←#.DRC.Wait ⍺ 10000:⍺ ∇ ⍵ (2⊃⍵)≡⍵[1]⌷4↑cw:0 cw} :If 0=1⊃r←#.DRC.Send cmd cmd ⍝ 3 ⍝ r∧←1≡c←cmd waitfor(1 3 4)(0 'Sent' 0) :AndIf 0=⊃r←cmd waitfor(1 3 4)(0 'Receive'(⌽cmd)) r←0 :Else Log'Client ',cmd,' failed ',r ⍝ r is set :EndIf ∇ ∇ {r}←m Client name;cmds;r;c r←0 :If 0=1⊃r←#.DRC.Clt name'localhost' 5000 cmds←(⊂name,'.'),¨'X',¨8{(-⍺)↑(⍺⍴'0'),⍕⍵}¨⍳m :If ∧/0≡¨r←CmdWait¨cmds Log'Client'name :EndIf c←#.DRC.Close name :Else r←0 Log'Client ',name,' Failed to connect' :EndIf res,←0=⊃r ∇ ∇ r←TestPause;sid;port;cons;cmds;c r←1 show←0 (port cons cmds)←5000 10 2 sid←Server&'S1' 0 0 port {}CControl'START'port c←⎕TSYNC(⊂cmds port)Client1&¨cons⍴⊂'' r∧←∧/0≡¨⊃¨c ⍝ Pause = 1 mean keep socket open but do not accept new connection in conga ⍝ Pause = 2 mean close socket create new socket when resuming. r∧←0 Assert⊃#.DRC.SetProp'S1' 'Pause' 2 c←⎕TSYNC(⊂cmds port)Client1&¨cons⍴⊂'' r∧←∧/1=¨⊃¨c r∧←0 Assert⊃#.DRC.SetProp'S1' 'Pause' 0 c←⎕TSYNC(⊂cmds port)Client1&¨cons⍴⊂'' r∧←∧/0≡¨⊃¨c c←CControl'STAT'port {}##.DRC.Close'S1' ⎕TSYNC sid Report r ∇ ∇ r←TestReadyList2 arg;n;m;ready;cons;ts;tc;tlist n m ready show←arg,(⍴arg)↓2 4 1 0 {}#.DRC.Close¨#.DRC.Names'.' res←⍬ r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 2 r∧←0 2 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' cons←'C',¨8{(-⍺)↑(⍺⍴'0'),⍕⍵}¨⍳n ts←ServerThread&'S1'n m ready ⎕DL 1 tc←m Client&¨cons :While ∨/tc∊⎕TNUMS ⍝ wait for all client threads to finish ⎕DL 0.5 :EndWhile ⎕TSYNC tc r∧←0 Assert⊃c←#.DRC.Close'S1' ⎕TSYNC ts ⍝test :If ~r∧←∧/res res :EndIf Report r ∇ ∇ r←TestReadyList arg;n;m;c;cons;cmds;res;name;data;recv;sendrecv;todo;tlist;i;ci;disconnect;connect;respond;ready;send;recvm;sendm;rs;rr;rt;respondm;last;timing;waitfor;results;show;log n m ready show←arg,(⍴arg)↓2 4 1 0 r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 2 r∧←0 2 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 ⍝('ReadyList' 1) show/'Server Started ',('failed' 'ok')[⎕IO+r] :If ready r∧←0 Assert⊃c←#.DRC.SetProp'S1' 'FIFOMode' 1 :EndIf results←3 2⍴(1 3 4)(0 'Connect' 0)(1 3 4)(0 'Error' 1119)(1 3)(0 'Receive') cons←'C',¨8{(-⍺)↑(⍺⍴'0'),⍕⍵}¨⍳n cmds←'X',¨8{(-⍺)↑(⍺⍴'0'),⍕⍵}¨⍳m log←{show/(40↑⍺),('failed' 'ok')[⎕IO+⍵]} waitfor←{(2⊃⍵)≡⍵[1]⌷c←#.DRC.Wait ⍺ 1000:1 ⋄ c} connect←{0=1⊃c←#.DRC.Clt ⍵'localhost' 5000:1 ⋄ 1111=1⊃c:∇ ⍵ ⋄ 0≠1⊃c:c} disconnect←{0≠⊃c←#.DRC.Close ⍵:c ⋄ 1} name←{(⊃cons[1⊃⍵]),'.',⊃cmds[2⊃⍵]} data←{'Test ',,⍕⍵} send←{0≠⊃#.DRC.Send(name ⍵)(data ⍵)3:¯1 0 'Sent' 0≢(⊂1 3 4)⌷c←#.DRC.Wait(name ⍵)10000:¯2 1 } recv←{100=⊃z←#.DRC.Wait(name ⍵)100000:∇ ⍵ 0 'Receive'(⌽data ⍵)≡(⊂1 3 4)⌷z:1 ¯2} sendm←{(⍵⌷rs)←send ⍵} recvm←{(⍵⌷rr)←recv ⍵} sendrecv←{0≠⊃#.DRC.Send(name ⍵)(data ⍵):¯1 (⍵⌷res)←recv ⍵} respond←{0 'Receive'≢(⊂1 3)⌷c←#.DRC.Waitt'S1' 10000:¯1 ⍝(1<⍴,⍵)∧((data ⍵)≢4⊃c):¯2 ⍝⎕←4⊃c 0≠⊃cr←#.DRC.Respond(2⊃c)(⌽4⊃c):¯3 timing,←5 2⊃c 1 } respondm←{(⍵⌷rt)←respond ⍵} todo←{⍵[(⍴⍵)?⍴⍵]},⍳n m 'Client connect 'log r∧←∧/1≡¨c←connect¨cons ⍝ Client connect 'Server connections 'log r∧←∧/1≡¨c←((⍴cons)⍴⊂'S1')waitfor¨⊂results[1;] ⍝ Server side wait for connection rs←rr←rt←n m⍴0 timing←⍬ {}sendm¨todo ⍝ Client send all commands 'Send 'log r∧←∧/∧/rs=1 tlist←recvm&¨todo ⍝ Client wait for all answers Threaded {}respondm¨todo ⍝ Server respond all commands 'Respond 'log r∧←∧/∧/rt=1 :While ∨/tlist∊⎕TNUMS ⍝ wait for all client threads to finish ⎕DL 0.5 :EndWhile 'Recv 'log r∧←∧/∧/rr=1 'In Order 'log r∧←∧/{0≤(1↓⍵)-¯1↓⍵}timing 'Disconnect 'log r∧←∧/1≡¨c←disconnect¨cons ⍝ close all client connections 'Disconnected 'log r∧←∧/1≡¨c←((⍴cons)⍴⊂'S1')waitfor¨⊂results[2;] ⍝ Server side wait for connectiona to close r∧←0 Assert⊃c←#.DRC.Close'S1' Report r ∇ ∇ r←TestEndpoints;c;EndPoints;Allowed;ep r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 2 r∧←0 2 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 Assert⊃c←#.DRC.GetProp'.' 'TCPLookup' '' 80 EndPoints←⍬~⍨{'IPv6'≡1⊃⍵:(1⊃⍵)(1↓¯4↓2⊃⍵) ⋄ 'IPv4'≡1⊃⍵:(1⊃⍵)(¯3↓2⊃⍵) ⋄ ⍬}¨2⊃c Allowed←((⍴EndPoints)⍴1 0)/EndPoints r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 'S2'Assert c←#.DRC.Srv'S2' '' 5001 'BlkText' 10000('Magic'(#.DRC.Magic'TRex'))('AllowEndpoints'(↓{(⊃⍺)(¯1↓⊃,/(2⊃¨Allowed[⍵]),¨('/29,' '/120,')[⎕IO+⍺≡⊂'IPv6'])}⌸1⊃¨Allowed)) :For ep :In EndPoints r∧←0 Assert⊃c←#.DRC.Clt'C1'(2⊃ep)5000 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 Assert⊃c←#.DRC.Clt'C2'(2⊃ep)5001 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 :If ∨/Allowed∊⊂ep r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'S2' 100 r∧←0 Assert⊃c←#.DRC.Close'C2' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('S2')100 :Else r∧←100 'TIMEOUT'Assert(⊂1 2)⌷c←#.DRC.Wait'S2' 100 r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('C2')100 :EndIf ⍝#.DRC.GetProp(2⊃c)'PeerAddr' r∧←0 Assert⊃c←#.DRC.Close'C1' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('S1')100 :EndFor r∧←0 Assert⊃c←#.DRC.Close'S1' r∧←0 Assert⊃c←#.DRC.Close'S2' Report r ∇ ∇ r←TestSentCompleteText;c1;c;c2;c3 r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 3 r∧←0 3 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 'C1'Assert c←#.DRC.Clt'C1' 'localhost' 5000 'BlkText' 10000('Magic'(#.DRC.Magic'TRex')) r∧←0 Assert⊃c1←#.DRC.Send'C1' 'test 1 1' r∧←0 Assert⊃c2←#.DRC.Send'C1' 'test 1 2' 3 r∧←0 Assert⊃c3←#.DRC.Send'C1' 'test 1 3' 3 r∧←0 'Sent' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 'Block' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃c)(4⊃c) r∧←0 'Block' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃c)(4⊃c) r∧←0 'Block' 'test 1 3'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃c)(4⊃c) r∧←0 'Sent' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 'Block' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 'Block' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 'Block' 'test 1 3'Assert(⊂1 3 4)⌷c←#.DRC.Wait'C1' 100 r∧←0 Assert⊃c←#.DRC.Close'C1' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('S1')100 r∧←0 Assert⊃c←#.DRC.Close'S1' Report r ∇ ∇ r←TestSentCompleteCMD;c1;c;c2;c3 r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 3 r∧←0 3 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 r∧←0 'C1'Assert c←#.DRC.Clt'C1' 'localhost' 5000 r∧←0 Assert⊃c1←#.DRC.Send'C1' 'test 1 1' r∧←0 Assert⊃c2←#.DRC.Send'C1' 'test 1 2' 3 r∧←0 Assert⊃c3←#.DRC.Send'C1' 'test 1 3' 3 r∧←0 'Sent' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Respond(2⊃c)(4⊃c) r∧←0 'Receive' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Respond(2⊃c)(4⊃c) r∧←0 'Receive' 'test 1 3'Assert(⊂1 3 4)⌷c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Respond(2⊃c)(4⊃c) r∧←0 'Receive' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c1)100 r∧←0 'Receive' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 r∧←0 'Receive' 'test 1 3'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c3)100 r∧←0 Assert⊃c←#.DRC.Close'C1' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait('S1')100 r∧←0 Assert⊃c←#.DRC.Close'S1' Report r ∇ ∇ r←TestThreaded;c2;c1;c3 r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'ReadyStrategy' 4 r∧←0 4 Assert c←#.DRC.GetProp'.' 'ReadyStrategy' r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 r∧←0 Assert⊃c←#.DRC.SetProp'S1' 'ConnectionOnly' 1 r∧←(0(,1))Assert c←#.DRC.GetProp'S1' 'ConnectionOnly' r∧←0 'C1'Assert c←#.DRC.Clt'C1' 'localhost' 5000 r∧←0 Assert⊃c←#.DRC.Send'C1' 'test 1 1' r∧←0 Assert⊃c←#.DRC.Send'C1' 'test 1 2' r∧←0 'C2'Assert c←#.DRC.Clt'C2' 'localhost' 5000 r∧←0 Assert⊃c←#.DRC.Send'C2' 'test 2 1' r∧←0 Assert⊃c←#.DRC.Send'C2' 'test 2 2' r∧←0 'C3'Assert c←#.DRC.Clt'C3' 'localhost' 5000 r∧←0 Assert⊃c←#.DRC.Send'C3' 'test 3 1' r∧←0 Assert⊃c←#.DRC.Send'C3' 'test 3 2' 1 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c1←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 1 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c1)100 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c2←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 2 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 r∧←0 'Connect' 0 Assert(⊂1 3 4)⌷c3←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 3 1'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c3)100 r∧←100 'TIMEOUT' ''Assert c←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'test 1 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c1)100 r∧←0 'Receive' 'test 2 2'Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 c←#.DRC.Wait(2⊃c3)100 :If 0 'Error' 1119≡(⊂1 3 4)⌷c c←#.DRC.Wait(2⊃c3)100 :EndIf r∧←0 'Receive' 'test 3 2'Assert(⊂1 3 4)⌷c r∧←100 'TIMEOUT' ''Assert c←#.DRC.Wait(2⊃c1)100 r∧←100 'TIMEOUT' ''Assert c←#.DRC.Wait(2⊃c2)100 r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c3)100 r∧←100 'TIMEOUT' ''Assert c←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Close'C1' r∧←0 Assert⊃c←#.DRC.Close'C2' r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c1)100 r∧←0 'Error' 1119 Assert(⊂1 3 4)⌷c←#.DRC.Wait(2⊃c2)100 r∧←0 Assert⊃c←#.DRC.Close'S1' Report r ∇ ∇ r←Connect(addr port srv prot);c;c1 r←1 r∧←0≡⊃c←#.DRC.Clt''addr port,(0<⍴prot)/(⊂'Protocol'prot) r∧←0 'Connect' 0≡(⊂1 3 4)⌷c1←4↑#.DRC.Wait srv 100 r∧←0≡⊃#.DRC.Close 2⊃c r∧←0 'Error' 1119≡(⊂1 3 4)⌷c1←4↑#.DRC.Wait(srv)100 ∇ ∇ r←TestGetAddrInfo;srvs;tests;res;rr;c r←1 srvs←('SA' '' 5000)('S4' '' 5004('Protocol' 'ipv4'))('S6' '' 5006('Protocol' 'ipv6')) r←∧/rr←{0(1⊃⍵)≡#.DRC.Srv ⍵}¨srvs :If ~r 'Failed: ',⍕rr/srvs :EndIf tests←('localhost' '127.0.0.1' '::1' '')∘.{(⊂⍺),⍵}{⍵[3 1]}¨srvs res←(⍴tests)⍴1 res[2;3]←0 res[3;2]←0 rr←Connect¨tests,¨⊂⊂'' r∧←res Assert rr r∧←((⍴srvs)⍴0)Assert⊃¨c←#.DRC.Close¨1⊃¨srvs Report r ∇ ∇ r←TestProtocol;srvs;tests;res;rr;c r←1 srvs←('SA' '' 5000)('S4' '' 5004('Protocol' 'ipv4'))('S6' '' 5006('Protocol' 'ipv6')) r←∧/rr←{0(1⊃⍵)≡#.DRC.Srv ⍵}¨srvs :If ~r 'Failed: ',⍕rr/srvs :EndIf tests←(('localhost'⍬)('localhost' 'ip')('localhost' 'ipv4')('localhost' 'ipv6'))∘.{(⍺,⍵)[1 3 4 2]}{⍵[3 1]}¨srvs res←(⍴tests)⍴1 res[3;3]←0 res[4;2]←0 rr←Connect¨tests r∧←res Assert rr r∧←((⍴srvs)⍴0)Assert⊃¨c←#.DRC.Close¨1⊃¨srvs Report r ∇ ∇ r←TestProgress;c;rs;cmd;rc r←1 r∧←0 Assert⊃c←#.DRC.SetProp'.' 'EventMode' 1 r∧←0 'S1'Assert c←#.DRC.Srv'S1' '' 5000 r∧←0 'C1'Assert c←#.DRC.Clt'C1' '' 5000 r∧←0 Assert⊃c←#.DRC.Send'C1' 'testing 1 2 3' cmd←2⊃c r∧←0 'Connect'Assert(⊂1 3)⌷c←#.DRC.Wait'S1' 100 r∧←0 'Receive' 'testing 1 2 3'Assert(⊂1 3 4)⌷rs←#.DRC.Wait'S1' 100 r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('10%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('20%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('30%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('40%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('50%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('60%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('70%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('80%') r∧←0 Assert⊃c←#.DRC.Progress(2⊃rs)('90%') r∧←0 'Progress' '10%'Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←0 'Progress' '20%'Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←0 'Progress' '30%'Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←0 'Progress' '40%'Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←0 Assert⊃c←#.DRC.Respond(2⊃rs)(⌽4⊃rs) ⎕DL 0.1 r∧←0 'Receive'(⌽'testing 1 2 3')Assert(⊂1 3 4)⌷rc←#.DRC.Wait cmd 100 r∧←1010 Assert⊃rc←#.DRC.Wait cmd 100 r∧←0 Assert⊃#.DRC.Close'C1' r∧←0 'Closed' 1119 Assert(⊂1 3 4)⌷rs←#.DRC.Wait'S1' 100 r∧←0 'Timeout' 100 Assert(⊂1 3 4)⌷rs←#.DRC.Wait'S1' 100 r∧←0 Assert⊃#.DRC.Close'S1' Report r ∇ ∇ r←TestUDPSimple;c;addrs;rc;con2;con1;data;a;sock r←1 r∧←0 Assert⊃c←#.DRC.GetProp'.' 'Ipv4Addrs' addrs←(2⊃c)[;2] ⍝addrs←(¯2↓¨2⊃¨{('IPv4'∘≡∘⊃¨⍵)/⍵}2⊃c) r∧←0 'UdpS'Assert c←#.DRC.Srv'UdpS' '' 5000 'udp' 10000('Protocol' 'ipv4') r∧←0 Assert⊃c←#.DRC.Clt'UdpC' '127.0.0.1' 5000 'udp' 10000('Protocol' 'ipv4') con1←2⊃c r∧←0 Assert⊃c←#.DRC.Send con1'Testing Udp1' r∧←0 Assert⊃c←#.DRC.Send'UdpC'('127.0.0.1' 5000 'Testing Udp2') con2←2⊃c r∧←0 'Block'('Testing Udp1')Assert(⊂1 3 4)⌷rc←#.DRC.Wait'UdpS' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃rc)'Testing Udp1' r∧←0 'Block'('Testing Udp2')Assert(⊂1 3 4)⌷rc←#.DRC.Wait'UdpS' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃rc)'Testing Udp2' r∧←0 'Block'('Testing Udp1')Assert(⊂1 3 4)⌷rc←#.DRC.Wait con1 100 r∧←0 'Block'('Testing Udp2')Assert(⊂1 3 4)⌷rc←#.DRC.Wait con2 100 :For a :In addrs data←'Testing Udp ',a r∧←0 Assert⊃c←#.DRC.Send'UdpC'(a 5000 data) con2←2⊃c r∧←0 'Block'data Assert(⊂1 3 4)⌷rc←#.DRC.Wait'UdpS' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃rc)(⌽data) r∧←0 'Block'(⌽data)Assert(⊂1 3 4)⌷rc←#.DRC.Wait con2 100 :EndFor sock←⍬ :For a :In addrs data←'Testing Udp ',a r∧←0 Assert⊃c←#.DRC.Clt''a 5000 'udp' 10000('Protocol' 'ipv4') con2←2⊃c sock,←⊂{(¯1+⍵⍳'.')↑⍵}con2 r∧←0 Assert⊃c←#.DRC.Send con2 data r∧←0 'Block'data Assert(⊂1 3 4)⌷rc←#.DRC.Wait'UdpS' 100 r∧←0 Assert⊃c←#.DRC.Send(2⊃rc)(⌽data) r∧←0 'Block'(⌽data)Assert(⊂1 3 4)⌷rc←#.DRC.Wait con2 100 :EndFor :For n :In #.DRC.Names'.' 'Connection: ',n :For l :In #.DRC.Names n ' ',⍕decodeAddr l :EndFor :EndFor r∧←∧/0=⊃¨#.DRC.Close¨sock r∧←0 Assert⊃c←#.DRC.Close'UdpC' r∧←0 Assert⊃c←#.DRC.Close'UdpS' Report r ∇ ∇ r←TestWebSocket;c;port;wscon;len;data;c1;Features;nl;drt r←1 to83←{⍵+¯256×⍵>127} nl←⎕UCS 13 10 port←8088 Features←1 ⍝ Feature 0=APL negotiate 1=AutoUpgrade c←#.DRC.Srv'S1' ''port'http' 450000 r∧←0 'S1'Assert c :If r=1 r∧←0 Assert⊃c←#.DRC.SetProp'S1' 'WSFeatures'Features ⍝ Set feature for server applies to all incomming connections c←#.DRC.Clt'C1' 'localhost'port'http' 450000 r∧←0 'C1'Assert c :If r=1 r∧←0 Assert⊃c←#.DRC.SetProp'C1' 'WSFeatures'Features c←#.DRC.Wait'S1' 1000 r∧←0 'Connect'Assert c[1 3] ⍝ Client requests to upgrade the connection 4th arg is extra headers remember to add nl r∧←0 Assert⊃c←#.DRC.SetProp'C1' 'WSUpgrade'('/' 'localhost'('BHCHeader: Gil',nl)) c←#.DRC.Wait'S1' 1000 :If 0 'WSUpgrade'≡c[1 3] ⍝ Auto upgrade event 4⊃c is the Incomming request but connection have been upgraded r∧←1 :ElseIf 0 'WSUpgradeReq'≡c[1 3] ⍝ Negotiate inspect headers and accept request with the extra headers you need. :If 0<≢4⊃c r∧←0 Assert⊃c1←#.DRC.SetProp(2⊃c)'WSAccept'((4⊃c)('GILHeader: bhc',nl)) :EndIf :Else r←0 :EndIf wscon←2⊃c ⍝ test c←#.DRC.Wait'C1' 1000 ⍝ returns WSUpgrade and 4⊃c is the peers accept headers, WSResponse 4⊃c is the same but you have to accept the upgrade. :If 0 'WSResponse'≡c[1 3] r∧←0 Assert⊃c1←#.DRC.SetProp(2⊃c)'WSAccept'((4⊃c)'') :EndIf :For drt :In 80 160 320 :For len :In 0 10 124 125 126 127 128 65535 65536 70000 data←drt utf8 len ⍝ r∧←0 Assert⊃c←#.DRC.Send'C1'(data 1) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 1 1)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Send wscon(data 1) c←#.DRC.Wait'C1' 1000 r∧←0 'WSReceive'(data 1 1)Assert c[1 3 4] :EndFor :EndFor :For offset :In -⎕IO+0 128 :For len :In 0 10 124 125 126 127 128 65535 65536 70000 data←offset+len⍴⍳256 r∧←0 Assert⊃c←#.DRC.Send'C1'(data 1) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'((to83 data)1 2)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Send wscon(data 1) c←#.DRC.Wait'C1' 1000 r∧←0 'WSReceive'((to83 data)1 2)Assert c[1 3 4] :EndFor :EndFor :For drt :In 80 160 320 :For len :In 0 10 124 125 126 127 128 65535 65536 70000 data←drt utf8 len ⍝ Fin←len=70000 r∧←0 Assert⊃c←#.DRC.Send'C1'(data Fin) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data Fin 1)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Send wscon(data Fin) c←#.DRC.Wait'C1' 1000 r∧←0 'WSReceive'(data Fin 1)Assert c[1 3 4] :EndFor :EndFor :For offset :In -⎕IO+0 128 :For len :In 0 10 124 125 126 127 128 65535 65536 70000 data←offset+len⍴⍳256 Fin←len=70000 r∧←0 Assert⊃c←#.DRC.Send'C1'(data Fin) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'((to83 data)Fin 2)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Send wscon(data Fin) c←#.DRC.Wait'C1' 1000 r∧←0 'WSReceive'((to83 data)Fin 2)Assert c[1 3 4] :EndFor :EndFor ⍝ test wrong type data←80 utf8 1000 ⍝ r∧←0 Assert⊃c←#.DRC.Send'C1'(data 0) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 0 1)Assert c[1 3 4] data←(-128+⎕IO)+1000⍴⍳256 r∧←1004 Assert⊃c←#.DRC.Send'C1'(data 1) data←80 utf8 1000 ⍝ r∧←0 Assert⊃c←#.DRC.Send'C1'(data 1) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 1 1)Assert c[1 3 4] ⍝ test wrong type data←(-128+⎕IO)+1000⍴⍳256 r∧←0 Assert⊃c←#.DRC.Send'C1'(data 0) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 0 2)Assert c[1 3 4] data←80 utf8 1000 ⍝ r∧←1004 Assert⊃c←#.DRC.Send'C1'(data 1) data←(-128+⎕IO)+1000⍴⍳256 r∧←0 Assert⊃c←#.DRC.Send'C1'(data 1) c←#.DRC.Wait'S1' 1000 r∧←0 'WSReceive'(data 1 2)Assert c[1 3 4] r∧←0 Assert⊃c←#.DRC.Close'C1' c←#.DRC.Wait'S1' 10000 r∧←0 'Error' 1119 Assert c[1 3 4] :EndIf r∧←0 Assert⊃c←#.DRC.Close'S1' :EndIf ∇ ∇ r←Run;c r←1 show←0 StopOnError←1 Errors←⍬ ⍝c←#.DRC.Init'' ⍝r∧←0=⊃c r∧←0 Assert⊃c←#.DRC.SetProp'.' 'EventMode' 0 ⍝ Close any extant connections c←#.DRC.Close¨#.DRC.Names'.' r∧←TestThreaded c←#.DRC.Close¨#.DRC.Names'.' r∧←TestSentCompleteCMD c←#.DRC.Close¨#.DRC.Names'.' r∧←TestSentCompleteText c←#.DRC.Close¨#.DRC.Names'.' r∧←TestEndpoints c←#.DRC.Close¨#.DRC.Names'.' r∧←TestSendFile c←#.DRC.Close¨#.DRC.Names'.' r∧←TestSendFileBlk c←#.DRC.Close¨#.DRC.Names'.' r∧←TestPause c←#.DRC.Close¨#.DRC.Names'.' r∧←TestGetAddrInfo c←#.DRC.Close¨#.DRC.Names'.' r∧←TestProtocol c←#.DRC.Close¨#.DRC.Names'.' r∧←TestRaw c←#.DRC.Close¨#.DRC.Names'.' r∧←TestWebSocket c←#.DRC.Close¨#.DRC.Names'.' r∧←TestReadyList2 4 8 1 0 c←#.DRC.Close¨#.DRC.Names'.' r∧←TestProgress :If 0<⍴Errors Errors :EndIf ∇ ∇ r←decodeAddr addr;parts parts←¯2↑'.:'{m←(⊃⍺),⍵ ⋄ 1↓¨(m∊⍺)⊂m}addr r←(base64 1⊃parts)(dec 2⊃parts) ∇ base64←{⎕IO ⎕ML←0 1 ⍝ Base64 encoding and decoding as used in MIME. chars←'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' bits←{,⍉(⍺⍴2)⊤⍵} ⍝ encode each element of ⍵ in ⍺ bits, ⍝ and catenate them all together part←{((⍴⍵)⍴⍺↑1)⊂⍵} ⍝ partition ⍵ into chunks of length ⍺ 0=2|⎕DR ⍵:2∘⊥∘(8∘↑)¨8 part{(-8|⍴⍵)↓⍵}6 bits{(⍵≠64)/⍵}chars⍳⍵ ⍝ decode a string into octets four←{ ⍝ use 4 characters to encode either 8=⍴⍵:'=='∇ ⍵,0 0 0 0 ⍝ 1, 16=⍴⍵:'='∇ ⍵,0 0 ⍝ 2 chars[2∘⊥¨6 part ⍵],⍺ ⍝ or 3 octets of input } cats←⊃∘(,/)∘((⊂'')∘,) ⍝ catenate zero or more strings cats''∘four¨24 part 8 bits ⍵ } dec←{⎕IO ⎕ML←0 1 ⍝ Decimal from hexadecimal ⍺←0 ⍝ unsigned by default. 1<⍴⍴⍵:↑⍺ ∇¨↓⍵ ⍝ vector-wise: 0=≢⍵:0 ⍝ dec'' → 0. 1≠≡,⍵:⍺ ∇¨⍵ ⍝ simple-array-wise: ' '=⊃⍵:⍺ ∇ 1↓⍵ ⍝ ignoring leading and ' '=⊃⌽⍵:⍺ ∇ ¯1↓⍵ ⍝ ... trailing blanks. ' '∊⍵:⍺ ∇¨{1↓¨(⍵=' ')⊂⍵}' ',⍵ ⍝ blank-separated: v←16|'0123456789abcdef0123456789ABCDEF'⍳⍵ ⍝ hex digits. 11::'Too big'⎕SIGNAL 11 ⍝ number too big. (16⊥v)-⍺×(8≤⊃v)×16*≢v ⍝ (signed) decimal number. } :EndNamespace ",16227,True,3507.8401054027804,median "1 1 40 1 45.89 -1 0 2 40 35 1 61.06 32 1 3 35 43 1 48.55 -1 2 1 1 40 2 94.93 -1 0 2 40 35 2 44.94 -1 1 3 35 43 2 86.57 -1 2 1 1 40 3 16.49 32 0 2 40 35 3 59.62 -1 1 3 35 43 3 96.64 32 2 1 1 40 4 75.77 32 0 2 40 35 4 39.23 -1 1 3 35 43 4 14.18 32 2 4 2 36 1 51.48 -1 3 5 36 45 1 22.67 -1 4 6 45 56 1 81.81 32 5 7 45 33 1 28.76 32 6 8 45 35 1 96.42 -1 7 4 2 36 2 91.37 32 3 5 36 45 2 15.87 -1 4 6 45 56 2 88.25 -1 5 7 45 33 2 64 -1 6 8 45 35 2 100 32 7 4 2 36 3 66.11 32 3 5 36 45 3 45.79 -1 4 6 45 56 3 9.019 32 5 7 45 33 3 100 -1 6 8 45 35 3 39.88 32 7 4 2 36 4 69.23 66 3 5 36 45 4 22.91 -1 4 6 45 56 4 86.43 66 5 7 45 33 4 21.01 66 6 8 45 35 4 92.11 -1 7 9 3 22 1 72.8 -1 8 10 22 39 1 100 -1 9 9 3 22 2 94.73 32 8 10 22 39 2 97.68 32 9 9 3 22 3 91.78 -1 8 10 22 39 3 21.88 -1 9 9 3 22 4 100 32 8 10 22 39 4 84.9 -1 9 11 4 40 1 56.15 -1 10 12 40 41 1 36.74 -1 11 13 41 23 1 100 32 0 14 23 36 1 57.2 -1 0 15 23 39 1 30.98 -1 0 16 23 63 1 40.43 32 12 11 4 40 2 89.68 -1 10 12 40 41 2 70.77 32 11 13 41 23 2 91.91 -1 0 14 23 36 2 85.47 -1 0 15 23 39 2 7.366 -1 0 16 23 63 2 52.38 -1 12 11 4 40 3 42.02 32 10 12 40 41 3 55.67 -1 11 13 41 23 3 21.52 -1 0 14 23 36 3 40.4 32 0 15 23 39 3 44.43 -1 0 16 23 63 3 90.93 32 12 11 4 40 4 100 -1 10 12 40 41 4 78.7 32 11 13 41 23 4 13.19 32 0 14 23 36 4 58.45 -1 0 15 23 39 4 25.9 -1 0 16 23 63 4 15.75 -1 12 17 5 29 1 56.89 -1 0 18 29 64 1 10.44 -1 13 17 5 29 2 32.3 32 0 18 29 64 2 44.52 -1 13 17 5 29 3 27.21 -1 0 18 29 64 3 19.6 -1 13 17 5 29 4 51.07 -1 0 18 29 64 4 23.61 32 13 19 6 33 1 39.67 32 14 20 33 51 1 82.67 -1 0 19 6 33 2 3.784 -1 14 20 33 51 2 33.71 -1 0 19 6 33 3 79.41 -1 14 20 33 51 3 68.55 -1 0 19 6 33 4 11.08 -1 14 20 33 51 4 56.16 -1 0 21 7 38 1 6.722 32 0 22 38 17 1 97.24 -1 0 23 17 46 1 47.24 32 15 24 17 62 1 100 -1 0 21 7 38 2 34.55 32 0 22 38 17 2 76.3 -1 0 23 17 46 2 14.86 -1 15 24 17 62 2 95.09 -1 0 21 7 38 3 61.97 -1 0 22 38 17 3 24.38 32 0 23 17 46 3 21.46 -1 15 24 17 62 3 77.45 32 0 21 7 38 4 65.57 32 0 22 38 17 4 8.951 -1 0 23 17 46 4 57.1 -1 15 24 17 62 4 53.39 32 0 25 8 25 1 100 32 16 26 25 36 1 100 -1 0 27 36 20 1 61.44 -1 17 28 20 55 1 100 32 0 29 20 60 1 16.61 -1 0 30 20 57 1 26.98 32 0 25 8 25 2 44.33 -1 16 26 25 36 2 91.97 -1 0 27 36 20 2 27.68 -1 17 28 20 55 2 45.03 -1 0 29 20 60 2 44.16 32 0 30 20 57 2 10.45 32 0 25 8 25 3 32.21 -1 16 26 25 36 3 77.91 -1 0 27 36 20 3 41.64 32 17 28 20 55 3 65.42 -1 0 29 20 60 3 93.27 32 0 30 20 57 3 18.3 -1 0 25 8 25 4 77.36 32 16 26 25 36 4 42.78 -1 0 27 36 20 4 85.82 -1 17 28 20 55 4 40.13 -1 0 29 20 60 4 67.28 -1 0 30 20 57 4 82.57 -1 0 31 9 38 1 100 -1 0 32 38 32 1 43.61 -1 18 33 32 40 1 36.2 -1 19 34 32 49 1 22.92 -1 0 31 9 38 2 77.19 -1 0 32 38 32 2 69.09 -1 18 33 32 40 2 49.14 -1 19 34 32 49 2 65.89 -1 0 31 9 38 3 8.33 32 0 32 38 32 3 64.07 -1 18 33 32 40 3 52.14 32 19 34 32 49 3 100 -1 0 31 9 38 4 81.9 -1 0 32 38 32 4 100 -1 18 33 32 40 4 51.66 32 19 34 32 49 4 100 -1 0 35 10 40 1 53.33 32 0 36 40 28 1 17.14 -1 20 37 28 50 1 58.9 -1 0 38 28 37 1 47.72 -1 21 35 10 40 2 40.38 -1 0 36 40 28 2 75.55 -1 20 37 28 50 2 93.95 -1 0 38 28 37 2 28.38 32 21 35 10 40 3 100 -1 0 36 40 28 3 82.57 -1 20 37 28 50 3 63.44 -1 0 38 28 37 3 56.47 -1 21 35 10 40 4 100 -1 0 36 40 28 4 64.29 48 20 37 28 50 4 59.27 48 0 38 28 37 4 39.47 48 21 39 11 18 1 36.54 32 22 40 18 35 1 56.7 32 0 41 35 53 1 23.29 -1 0 42 35 37 1 27.01 -1 23 43 35 52 1 24.85 -1 0 39 11 18 2 29.69 -1 22 40 18 35 2 63.75 -1 0 41 35 53 2 63.84 32 0 42 35 37 2 3.033 -1 23 43 35 52 2 100 -1 0 39 11 18 3 69.33 -1 22 40 18 35 3 60.44 -1 0 41 35 53 3 82.9 -1 0 42 35 37 3 100 -1 23 43 35 52 3 46.68 -1 0 39 11 18 4 5.396 -1 22 40 18 35 4 14.65 -1 0 41 35 53 4 22.19 -1 0 42 35 37 4 96.77 -1 23 43 35 52 4 100 32 0 44 12 44 1 15.82 32 0 45 44 34 1 22.83 -1 24 46 34 50 1 65.27 -1 25 47 34 39 1 94.86 -1 26 48 34 48 1 96.12 -1 0 44 12 44 2 12.46 32 0 45 44 34 2 45.1 -1 24 46 34 50 2 21.51 -1 25 47 34 39 2 57.55 32 26 48 34 48 2 40.86 -1 0 44 12 44 3 15.82 36 0 45 44 34 3 63.68 -1 24 46 34 50 3 100 -1 25 47 34 39 3 100 -1 26 48 34 48 3 91.7 -1 0 44 12 44 4 100 -1 0 45 44 34 4 23.84 -1 24 46 34 50 4 15.41 33 25 47 34 39 4 31.27 33 26 48 34 48 4 9.526 -1 0 49 13 44 1 76.82 -1 27 50 44 58 1 25.7 32 0 51 44 36 1 89.3 -1 0 52 44 63 1 48.77 -1 0 49 13 44 2 24.87 -1 27 50 44 58 2 39.89 32 0 51 44 36 2 46.97 -1 0 52 44 63 2 53.24 -1 0 49 13 44 3 40.36 -1 27 50 44 58 3 85.35 60 0 51 44 36 3 100 60 0 52 44 63 3 4.683 -1 0 49 13 44 4 61.07 32 27 50 44 58 4 80.38 -1 0 51 44 36 4 100 -1 0 52 44 63 4 17.91 -1 0 53 14 19 1 32.2 -1 28 54 19 38 1 16.68 -1 0 55 19 52 1 8.237 -1 0 53 14 19 2 38.22 -1 28 54 19 38 2 18.2 -1 0 55 19 52 2 100 32 0 53 14 19 3 29.92 32 28 54 19 38 3 62.95 -1 0 55 19 52 3 25.7 -1 0 53 14 19 4 78.83 32 28 54 19 38 4 59.02 -1 0 55 19 52 4 40.91 32 0 56 15 38 1 86.72 32 0 57 38 51 1 48.1 -1 0 56 15 38 2 98.35 -1 0 57 38 51 2 100 32 0 56 15 38 3 35.17 -1 0 57 38 51 3 84.43 -1 0 56 15 38 4 48.2 -1 0 57 38 51 4 6.475 -1 0 58 16 47 1 20.25 -1 0 59 47 44 1 63.37 -1 0 60 47 58 1 100 32 0 61 47 55 1 75.34 32 29 58 16 47 2 1.434 -1 0 59 47 44 2 65.37 -1 0 60 47 58 2 18.33 -1 0 61 47 55 2 80.82 -1 29 58 16 47 3 84.54 -1 0 59 47 44 3 87.78 -1 0 60 47 58 3 64.39 -1 0 61 47 55 3 100 -1 29 58 16 47 4 87.85 -1 0 59 47 44 4 100 -1 0 60 47 58 4 78.39 -1 0 61 47 55 4 91.67 -1 29 62 17 44 1 1.223 32 0 63 44 34 1 98.02 -1 0 64 34 43 1 54.48 -1 30 65 43 55 1 81.88 -1 0 62 17 44 2 96.67 -1 0 63 44 34 2 42.3 -1 0 64 34 43 2 31.36 32 30 65 43 55 2 90.54 -1 0 62 17 44 3 39.72 -1 0 63 44 34 3 87.3 -1 0 64 34 43 3 18.9 -1 30 65 43 55 3 73.24 -1 0 62 17 44 4 21.61 32 0 63 44 34 4 53.2 -1 0 64 34 43 4 92.94 -1 30 65 43 55 4 14.86 32 0 66 18 33 1 63.09 32 0 67 33 43 1 100 32 0 66 18 33 2 85.92 -1 0 67 33 43 2 97.53 -1 0 66 18 33 3 41.77 32 0 67 33 43 3 100 32 0 66 18 33 4 19.82 -1 0 67 33 43 4 76.88 32 0 68 19 41 1 85.46 -1 0 69 41 27 1 28.15 32 31 70 27 46 1 89.35 -1 0 71 27 64 1 41.37 -1 32 68 19 41 2 42.27 -1 0 69 41 27 2 41.58 -1 31 70 27 46 2 55.88 32 0 71 27 64 2 50.03 32 32 68 19 41 3 6.349 -1 0 69 41 27 3 9.996 -1 31 70 27 46 3 39.98 -1 0 71 27 64 3 94.88 -1 32 68 19 41 4 50.67 -1 0 69 41 27 4 16.74 -1 31 70 27 46 4 99.38 -1 0 71 27 64 4 22.96 53 32 72 20 45 1 40.11 32 33 73 45 33 1 75.47 32 0 74 33 45 1 3.532 -1 34 75 45 54 1 38.44 32 35 76 45 43 1 55.7 -1 36 77 45 46 1 100 -1 0 72 20 45 2 22.39 -1 33 73 45 33 2 47.65 32 0 74 33 45 2 41.24 -1 34 75 45 54 2 59.13 32 35 76 45 43 2 29.66 32 36 77 45 46 2 6.839 -1 0 72 20 45 3 81.09 -1 33 73 45 33 3 61.37 -1 0 74 33 45 3 45.05 37 34 75 45 54 3 80.52 -1 35 76 45 43 3 25.69 -1 36 77 45 46 3 47.84 -1 0 72 20 45 4 100 -1 33 73 45 33 4 8.483 -1 0 74 33 45 4 7.144 32 34 75 45 54 4 13.45 -1 35 76 45 43 4 100 -1 36 77 45 46 4 100 -1 0 78 21 24 1 80.72 32 0 79 24 43 1 40.24 -1 0 80 24 44 1 7.576 -1 37 81 24 58 1 46.11 32 0 78 21 24 2 81.99 -1 0 79 24 43 2 56.03 32 0 80 24 44 2 44.03 -1 37 81 24 58 2 18.36 32 0 78 21 24 3 67.67 -1 0 79 24 43 3 43.08 -1 0 80 24 44 3 50.93 -1 37 81 24 58 3 94.58 -1 0 78 21 24 4 81.34 33 0 79 24 43 4 33.75 33 0 80 24 44 4 15.99 -1 37 81 24 58 4 92.19 -1 0 82 22 34 1 12.64 -1 0 83 34 47 1 61.68 32 0 82 22 34 2 61.25 -1 0 83 34 47 2 16.35 -1 0 82 22 34 3 66.47 -1 0 83 34 47 3 93.49 -1 0 82 22 34 4 94.06 63 0 83 34 47 4 50.81 -1 0 84 23 30 1 47.23 -1 0 85 30 64 1 43.14 -1 0 86 30 47 1 31.07 -1 0 87 30 45 1 3.313 32 0 84 23 30 2 16.06 -1 0 85 30 64 2 48.21 -1 0 86 30 47 2 71.2 -1 0 87 30 45 2 60.17 -1 0 84 23 30 3 61.42 32 0 85 30 64 3 44.06 32 0 86 30 47 3 48.87 32 0 87 30 45 3 15.58 -1 0 84 23 30 4 61.75 71 0 85 30 64 4 84.49 -1 0 86 30 47 4 44.16 -1 0 87 30 45 4 17.56 -1 0 88 24 47 1 81.69 -1 0 89 47 40 1 52.06 32 38 88 24 47 2 11.14 -1 0 89 47 40 2 63.3 -1 38 88 24 47 3 94.82 -1 0 89 47 40 3 13.17 -1 38 88 24 47 4 64.92 -1 0 89 47 40 4 26.01 -1 38 90 25 35 1 100 32 0 91 35 40 1 12.03 -1 0 92 35 54 1 100 -1 39 93 35 57 1 47.17 32 40 90 25 35 2 97.49 32 0 91 35 40 2 98.94 -1 0 92 35 54 2 27.18 32 39 93 35 57 2 51.03 -1 40 90 25 35 3 15.82 -1 0 91 35 40 3 94.07 -1 0 92 35 54 3 89.51 32 39 93 35 57 3 34.07 -1 40 90 25 35 4 97.4 -1 0 91 35 40 4 6.812 -1 0 92 35 54 4 59.88 -1 39 93 35 57 4 26.23 -1 40 94 26 36 1 78.85 -1 0 95 36 45 1 76.69 -1 0 96 45 49 1 13.99 -1 0 97 45 35 1 90.87 -1 41 94 26 36 2 26.24 -1 0 95 36 45 2 13.58 -1 0 96 45 49 2 77.84 32 0 97 45 35 2 83.24 -1 41 94 26 36 3 64.91 -1 0 95 36 45 3 61.86 -1 0 96 45 49 3 100 -1 0 97 45 35 3 31.19 -1 41 94 26 36 4 100 32 0 95 36 45 4 49.85 -1 0 96 45 49 4 43.47 -1 0 97 45 35 4 17.32 -1 41 98 27 41 1 96.75 -1 42 99 41 39 1 25.93 -1 43 100 39 47 1 33.14 -1 44 101 47 60 1 23.94 32 45 98 27 41 2 66.44 32 42 99 41 39 2 100 32 43 100 39 47 2 67.76 -1 44 101 47 60 2 50.01 32 45 98 27 41 3 43.34 32 42 99 41 39 3 82.88 -1 43 100 39 47 3 36.34 32 44 101 47 60 3 14.29 -1 45 98 27 41 4 9.517 32 42 99 41 39 4 57.42 -1 43 100 39 47 4 94.88 -1 44 101 47 60 4 19.13 -1 45 102 28 26 1 55.07 -1 46 103 26 37 1 78.18 -1 47 104 37 31 1 29.9 -1 48 105 31 55 1 40.67 -1 0 106 31 34 1 48.39 32 0 102 28 26 2 35.45 -1 46 103 26 37 2 100 32 47 104 37 31 2 10.27 -1 48 105 31 55 2 10.7 -1 0 106 31 34 2 6.048 -1 0 102 28 26 3 22.87 -1 46 103 26 37 3 96.55 -1 47 104 37 31 3 94.8 -1 48 105 31 55 3 64.54 -1 0 106 31 34 3 100 -1 0 102 28 26 4 58.86 32 46 103 26 37 4 7.841 32 47 104 37 31 4 25.43 -1 48 105 31 55 4 20.39 -1 0 106 31 34 4 95.18 -1 0 107 29 46 1 7.493 -1 49 108 46 48 1 55.57 32 50 109 46 41 1 44.05 32 0 107 29 46 2 96.92 -1 49 108 46 48 2 40.94 -1 50 109 46 41 2 57.14 -1 0 107 29 46 3 78.09 -1 49 108 46 48 3 47.56 -1 50 109 46 41 3 78.13 -1 0 107 29 46 4 47.74 -1 49 108 46 48 4 48.37 -1 50 109 46 41 4 91.57 -1 0 110 30 48 1 100 32 0 111 48 33 1 94.19 -1 0 112 33 21 1 100 -1 0 113 21 62 1 100 32 0 114 21 51 1 38.72 32 51 115 21 40 1 100 -1 52 110 30 48 2 97.87 -1 0 111 48 33 2 69.66 -1 0 112 33 21 2 7.944 -1 0 113 21 62 2 45.77 -1 0 114 21 51 2 100 32 51 115 21 40 2 100 -1 52 110 30 48 3 49.07 -1 0 111 48 33 3 79.72 32 0 112 33 21 3 94.3 32 0 113 21 62 3 64.96 -1 0 114 21 51 3 67.98 -1 51 115 21 40 3 60.33 -1 52 110 30 48 4 89.39 -1 0 111 48 33 4 42.98 -1 0 112 33 21 4 8.653 91 0 113 21 62 4 96.18 -1 0 114 21 51 4 68.21 91 51 115 21 40 4 64.48 91 52 116 31 42 1 35.2 -1 0 117 42 33 1 72.66 -1 53 118 33 45 1 96.04 -1 54 119 45 59 1 9.712 32 0 116 31 42 2 100 32 0 117 42 33 2 76.73 -1 53 118 33 45 2 23.26 -1 54 119 45 59 2 23.61 -1 0 116 31 42 3 93.89 -1 0 117 42 33 3 90.72 -1 53 118 33 45 3 29.1 -1 54 119 45 59 3 15.74 32 0 116 31 42 4 7.337 -1 0 117 42 33 4 70.73 -1 53 118 33 45 4 73.85 -1 54 119 45 59 4 29.95 -1 0 120 32 35 1 27.57 -1 0 121 35 44 1 62.59 32 0 122 44 33 1 9.159 -1 0 123 33 57 1 43.85 32 0 124 33 36 1 100 -1 55 125 33 34 1 49.61 -1 56 126 33 35 1 51.52 -1 57 127 33 37 1 47.34 -1 0 128 33 38 1 17.19 -1 0 129 33 39 1 49.57 -1 58 130 33 40 1 100 -1 0 131 33 41 1 100 32 59 132 33 42 1 13.29 -1 0 133 33 43 1 100 32 60 134 33 44 1 97.07 32 0 135 33 45 1 75.29 -1 0 136 33 46 1 100 32 0 137 33 47 1 24.81 -1 0 138 33 48 1 73.2 32 61 139 33 49 1 50.42 -1 62 140 33 50 1 64.41 32 0 141 33 51 1 37.62 -1 0 142 33 52 1 59.24 -1 0 143 33 53 1 55.86 32 63 144 33 54 1 100 -1 0 145 33 55 1 52.66 32 0 146 33 56 1 73.53 -1 64 147 33 58 1 26.48 -1 0 148 33 59 1 83.83 -1 0 149 33 60 1 5.195 -1 65 150 33 61 1 91.25 -1 0 151 33 62 1 77.6 -1 0 152 33 63 1 50.41 -1 0 153 33 64 1 51.17 32 66 120 32 35 2 98.45 32 0 121 35 44 2 18.09 -1 0 122 44 33 2 21.95 -1 0 123 33 57 2 27.7 32 0 124 33 36 2 43.85 32 55 125 33 34 2 89.08 -1 56 126 33 35 2 22.97 32 57 127 33 37 2 83.14 -1 0 128 33 38 2 73.26 32 0 129 33 39 2 82.53 -1 58 130 33 40 2 10.41 -1 0 131 33 41 2 40.36 32 59 132 33 42 2 59.01 -1 0 133 33 43 2 3.182 -1 60 134 33 44 2 81.14 32 0 135 33 45 2 100 -1 0 136 33 46 2 55.05 -1 0 137 33 47 2 58.23 -1 0 138 33 48 2 26.58 -1 61 139 33 49 2 44.44 -1 62 140 33 50 2 8.734 -1 0 141 33 51 2 6.194 32 0 142 33 52 2 42.63 -1 0 143 33 53 2 15.36 -1 63 144 33 54 2 100 -1 0 145 33 55 2 100 -1 0 146 33 56 2 100 32 64 147 33 58 2 86.79 -1 0 148 33 59 2 81.52 -1 0 149 33 60 2 7.931 -1 65 150 33 61 2 91.79 32 0 151 33 62 2 96.9 -1 0 152 33 63 2 92.13 -1 0 153 33 64 2 85.87 -1 66 120 32 35 3 100 -1 0 121 35 44 3 19.11 -1 0 122 44 33 3 45.08 -1 0 123 33 57 3 39.23 32 0 124 33 36 3 46.71 -1 55 125 33 34 3 2.191 32 56 126 33 35 3 50.01 -1 57 127 33 37 3 74.86 -1 0 128 33 38 3 30.59 -1 0 129 33 39 3 85.93 -1 58 130 33 40 3 32.35 -1 0 131 33 41 3 63.21 -1 59 132 33 42 3 95.67 -1 0 133 33 43 3 100 -1 60 134 33 44 3 84.98 -1 0 135 33 45 3 75.02 -1 0 136 33 46 3 92.39 -1 0 137 33 47 3 100 -1 0 138 33 48 3 86.96 32 61 139 33 49 3 37.39 -1 62 140 33 50 3 67.47 -1 0 141 33 51 3 72.83 -1 0 142 33 52 3 73.05 -1 0 143 33 53 3 45.94 -1 63 144 33 54 3 100 -1 0 145 33 55 3 98.29 -1 0 146 33 56 3 32.13 32 64 147 33 58 3 51.27 -1 0 148 33 59 3 88.73 32 0 149 33 60 3 100 -1 65 150 33 61 3 96.47 -1 0 151 33 62 3 56.81 -1 0 152 33 63 3 21.44 -1 0 153 33 64 3 89.43 -1 66 120 32 35 4 50.08 -1 0 121 35 44 4 8.537 -1 0 122 44 33 4 8.318 -1 0 123 33 57 4 51.8 32 0 124 33 36 4 48.45 -1 55 125 33 34 4 59.15 32 56 126 33 35 4 53.24 32 57 127 33 37 4 40.6 -1 0 128 33 38 4 65.6 32 0 129 33 39 4 48.3 -1 58 130 33 40 4 3.517 -1 0 131 33 41 4 24.69 -1 59 132 33 42 4 61.03 32 0 133 33 43 4 69.2 -1 60 134 33 44 4 53.51 -1 0 135 33 45 4 12.96 32 0 136 33 46 4 89.12 32 0 137 33 47 4 13.55 -1 0 138 33 48 4 11.32 32 61 139 33 49 4 67.81 -1 62 140 33 50 4 100 32 0 141 33 51 4 88.92 -1 0 142 33 52 4 40.67 -1 0 143 33 53 4 77.74 -1 63 144 33 54 4 100 32 0 145 33 55 4 43.81 -1 0 146 33 56 4 73.74 32 64 147 33 58 4 48.16 -1 0 148 33 59 4 42.21 32 0 149 33 60 4 40.42 32 65 150 33 61 4 30.97 32 0 151 33 62 4 85.04 -1 0 152 33 63 4 9.494 -1 0 153 33 64 4 30.24 -1 66 154 4 25 4 77.84 43 67 154 4 25 1 72.97 -1 67 154 4 25 3 76.84 -1 67 155 46 19 2 62 -1 68 155 46 19 1 98.9 -1 68 155 46 19 3 53 -1 68 155 46 19 4 75.58 -1 68 156 19 35 4 64.22 30 0 156 19 35 3 41.18 -1 0 157 38 26 1 76.97 -1 69 157 38 26 2 41.83 -1 69 157 38 26 3 11.06 -1 69 158 11 17 4 76.3 31 70 158 11 17 3 10.94 -1 70 158 11 17 1 86.33 -1 70 158 11 17 2 58.32 -1 70 159 26 32 4 27.61 -1 71 159 26 32 2 32.83 -1 71 159 26 32 1 25.96 -1 71 160 15 40 3 66.85 -1 0 160 15 40 4 99.48 -1 0 160 15 40 1 8.033 -1 0 160 15 40 2 29.62 -1 0 161 21 51 1 33.33 -1 0 161 21 51 2 16.45 -1 0 161 21 51 3 94.66 9 0 162 8 34 1 52.79 18 0 163 50 31 2 91.81 -1 0 164 32 47 3 64.76 -1 72 165 53 27 4 10.81 -1 0 166 49 40 2 16.44 -1 73 166 49 40 3 67.73 -1 73 166 49 40 1 81.48 -1 73 166 49 40 4 19.98 -1 73 167 60 55 4 51.42 43 74 167 60 55 2 98.44 39 74 167 60 55 3 6.774 -1 74 167 60 55 1 24.53 44 74 168 36 61 2 29.34 -1 0 169 7 60 3 95.21 -1 75 169 7 60 4 55.63 -1 75 170 25 26 1 97.74 41 0 170 25 26 2 63.01 -1 0 171 26 28 1 33.56 9 76 171 26 28 2 2.734 17 76 171 26 28 3 96.78 29 76 172 54 17 1 24.94 44 77 172 54 17 2 43.06 28 77 173 26 57 1 85.09 46 78 173 26 57 2 78.61 5 78 174 51 64 3 1.666 -1 0 174 51 64 2 58.57 -1 0 174 51 64 1 37.38 -1 0 175 46 29 1 31.81 -1 0 175 46 29 2 33.15 -1 0 175 46 29 4 27.54 -1 0 175 46 29 3 59.95 49 0 176 49 45 1 21.7 -1 0 176 49 45 4 6.212 -1 0 176 49 45 3 85.22 33 0 176 49 45 2 38.6 -1 0 177 3 54 2 40.69 -1 79 177 3 54 3 46.83 -1 79 177 3 54 1 80.88 -1 79 178 10 42 3 7.143 -1 0 179 21 25 2 95.4 18 0 179 21 25 3 68.51 24 0 179 21 25 1 5.223 -1 0 179 21 25 4 73.22 40 0 180 58 19 1 53.36 -1 0 180 58 19 2 62.17 -1 0 180 58 19 4 50.71 -1 0 180 58 19 3 60.02 -1 0 181 48 53 1 17.47 -1 0 182 3 32 1 34.17 -1 80 183 56 31 4 35.75 33 0 183 56 31 2 49.21 -1 0 183 56 31 1 70.11 -1 0 184 31 33 3 31.41 -1 81 185 49 22 1 10.94 9 0 185 49 22 4 22.28 -1 0 186 30 34 1 48.37 21 0 186 30 34 2 39.81 -1 0 187 54 63 4 64.66 -1 0 187 54 63 1 64.31 -1 0 187 54 63 3 45.98 -1 0 188 18 35 1 72.84 -1 0 188 18 35 4 34.27 -1 0 189 9 60 1 24.37 -1 82 189 9 60 2 9.443 12 82 189 9 60 4 91.91 -1 82 189 9 60 3 14.29 -1 82 190 30 62 1 16.54 -1 0 190 30 62 4 35.32 -1 0 190 30 62 3 2.271 -1 0 190 30 62 2 78.21 -1 0 191 28 46 4 24.25 -1 0 191 28 46 2 87.56 48 0 192 14 41 2 36.16 -1 83 192 14 41 4 5.563 -1 83 193 21 46 3 47.05 2 0 194 44 57 4 9.499 30 84 194 44 57 2 68.98 10 84 194 44 57 1 31.39 -1 84 194 44 57 3 75.94 -1 84 195 16 47 3 10.28 -1 0 195 16 47 2 25.79 -1 0 196 32 59 4 38.61 -1 0 ",16156,True,4478.472226971221,median "/* UpdatePartly.ino This will scroll text on the display similar to ScrollingText.ino example, Scrolling will be faster, because only the changing part of the display gets updated. Enable U8g2 16 bit mode (see FAQ) for larger text! Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U82glib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list // This example shows a scrolling text. // If U8G2_16BIT is not set (default), then the pixel width of the text must be lesser than 128 // If U8G2_16BIT is set, then the pixel width an be up to 32000 u8g2_uint_t offset; // current offset for the scrolling text u8g2_uint_t width; // pixel width of the scrolling text (must be lesser than 128 unless U8G2_16BIT is defined const char *text = ""U8g2 ""; // scroll this text from right to left void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); u8g2.begin(); u8g2.setFont(u8g2_font_helvB18_tr); // set the target font to calculate the pixel width width = u8g2.getUTF8Width(text); // calculate the pixel width of the text u8g2.setFontMode(0); // enable transparent mode, which is faster // draw the constant part of the screen // this will not be overwritten later u8g2.firstPage(); do { u8g2.drawUTF8(18, 20, ""[ U8g2 ]""); // This part will stay constantly on the screen } while ( u8g2.nextPage() ); } void drawText(void) { u8g2_uint_t x = offset; do { // repeated drawing of the scrolling text... u8g2.drawUTF8(x, 19, text); // draw the scolling text x += width; // add the pixel width of the scrolling text } while( x < u8g2.getDisplayWidth() ); // draw again until the complete display is filled } void loop(void) { int i; // write the scrolling text to the lower part of the display for( i = 0; i < 3; i++ ) { // draw to lines 0...23 (3*8-1) // draw to the upper part of the screen u8g2.setBufferCurrTileRow(i); u8g2.clearBuffer(); drawText(); // but write the buffer to the lower part (offset 4*8 = 32) u8g2.setBufferCurrTileRow(4+i); u8g2.sendBuffer(); } // calculate the new offset for the scrolling offset-=1; // scroll by one pixel if ( (u8g2_uint_t)offset < (u8g2_uint_t)-width ) offset = 0; // start over again delay(10); // do some small delay } ",16142,True,4862.570353600288,median "/* DirectAccess.ino Demonstrate how to interact with the internal buffer directly Warning: This example will not work with all graphics controller. It will work with SSD13xx, UC1xxx, ST7656 controller It will definitly not work with ST7920, T6962, RA8835. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list uint8_t background_images[8][32]; void setup(void) { uint8_t i; /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); u8g2.begin(); u8g2.setFlipMode(0); u8g2.setFont(u8g2_font_chroma48medium8_8r); u8g2.setFontPosBottom(); // create eight images for a background animation for( i = 0; i < 8; i++ ) { // setup buffer by starting with the first page u8g2.firstPage(); // render some graphics into the buffer u8g2.drawStr(0-i,8,""U8g2U""); // store four tiles from the start of the buffer content in some local memory // one tile has 8x8 pixel: 8 bytes, four tiles are 32 bytes. // note: the actual memory pattern depends on the target display memcpy(background_images[i], u8g2.getBufferPtr(), 32); } // revert back to basline pos u8g2.setFontPosBaseline(); } void drawBackground(uint8_t image_idx) { u8g2_uint_t src_idx, dest_idx, total; uint8_t *buf; total = u8g2.getBufferTileWidth(); total *= 8; // calculate width in pixel // get the pointer to the buffer. We will write the image to that buffer buf = u8g2.getBufferPtr(); // fill the buffer with the background image // repeat the image until the complete width is filled src_idx = 0; for( dest_idx = 0; dest_idx < total; dest_idx++ ) { buf[dest_idx] = background_images[image_idx][src_idx]; src_idx++; if ( src_idx >= 32 ) src_idx = 0; } } void drawLogo(void) { u8g2.setFontMode(1); // Transparent u8g2.setFontDirection(0); u8g2.setFont(u8g2_font_inb24_mf); u8g2.drawStr(0, 30, ""U""); u8g2.setFontDirection(1); u8g2.setFont(u8g2_font_inb30_mn); u8g2.drawStr(21,8,""8""); u8g2.setFontDirection(0); u8g2.setFont(u8g2_font_inb24_mf); u8g2.drawStr(51,30,""g""); u8g2.drawStr(67,30,""\\xb2""); u8g2.drawHLine(2, 35, 47); u8g2.drawHLine(3, 36, 47); u8g2.drawVLine(45, 32, 12); u8g2.drawVLine(46, 33, 12); } uint8_t image_idx = 0; uint8_t dir = 0; void loop(void) { // buffer clear is not required any more // this increase performance a little bit u8g2.setAutoPageClear(0); // draw the U8g2 logo with a custom background u8g2.firstPage(); do { drawBackground(image_idx); drawLogo(); } while ( u8g2.nextPage() ); // move the background around if ( dir == 0 ){ image_idx++; if ( image_idx == 7 ) { dir = 1; } } else { image_idx--; if ( image_idx == 0 ) { dir = 0; } } delay(10); } ",16331,True,4777.092637843627,median " #include // Needed to store stuff in Flash using PROGMEM #include ""FastLED.h"" // Fastled library to control the LEDs #include // How many leds are connected? #define NUM_LEDS 256 // Define the Data Pin #define DATA_PIN 5 // Define the array of leds CRGB leds[NUM_LEDS]; const long Heart00[] PROGMEM = { 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000 }; const long Heart01[] PROGMEM = { 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000 }; const long Heart02[] PROGMEM = { 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xff0000, 0xff0000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000 }; const long Heart03[] PROGMEM = { 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0x000000,0x000000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000, 0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000, 0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000, 0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000, 0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000 }; const long Heart04[] PROGMEM = { 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000, 0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000, 0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000, 0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000, 0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000, 0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000, 0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000, 0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000 }; const long Heart05[] PROGMEM = { 0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000, 0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000, 0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000, 0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000, 0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000, 0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000, 0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000, 0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000, 0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000, 0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000, 0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000, 0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000 }; const int fullMatrix[16][16] PROGMEM = { {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}, {31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16}, {32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47}, {63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48}, {64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79}, {95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80}, {96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111}, {127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112}, {128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143}, {159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144}, {160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175}, {191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176}, {192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207}, {223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208}, {224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239}, {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240} }; void setup() { srand(time(NULL)); FastLED.addLeds(leds, NUM_LEDS); // Init of the Fastled library FastLED.setBrightness(15); } void drawArray(long *arr){ FastLED.clear(); for(int i = 0; i < NUM_LEDS; i++) { leds[i] = pgm_read_dword(&(arr[i])); } FastLED.show(); delay(200); } void drawHeart(){ drawArray(Heart00); drawArray(Heart01); drawArray(Heart02); drawArray(Heart03); drawArray(Heart04); drawArray(Heart05); } void doFireworks(){ const int height PROGMEM = (rand() % (11 + 1 - 4)) + 4; int startPosition PROGMEM = (rand() % (12 + 1 - 3)) + 3; int delayedBy PROGMEM = (rand() % (100 + 1 - 50)) + 50; int row = 0; int startPositionCopy = startPosition; // launch firework for(int i = 0; i < height; i++){ FastLED.clear(); int r = rand() % 254; int g = rand() % 254; int b = rand() % 254; row = 15 - i; int rowCopy = row; int spark = 1; leds[pgm_read_word(&(fullMatrix[row][startPosition]))] = CRGB(r, g, b);; if(i == (height - 1)){ leds[pgm_read_word(&(fullMatrix[row][startPosition]))] = CRGB(r, g, b);; for(int j = 1; j <= 3; j++){ FastLED.clear(); r = rand() % 254; g = rand() % 254; b = rand() % 254; leds[pgm_read_word(&(fullMatrix[row + spark][startPosition - spark]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[row + spark][startPosition + spark]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[row - spark][startPosition - spark]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[row - spark][startPosition + spark]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[row + spark][startPosition]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[row - spark][startPosition]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[row][startPosition + spark]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[row][startPosition - spark]))] = CRGB(r, g, b); if(j >= 1 && j < 3){ r = rand() % 254; g = rand() % 254; b = rand() % 254; leds[pgm_read_word(&(fullMatrix[rowCopy + j][startPositionCopy]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[rowCopy - j][startPositionCopy]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[rowCopy][startPositionCopy + j]))] = CRGB(r, g, b); leds[pgm_read_word(&(fullMatrix[rowCopy][startPositionCopy - j]))] = CRGB(r, g, b); } FastLED.show(); delay(delayedBy); spark++; } } FastLED.show(); delay(delayedBy); } } void displayXTimes(void (*f)(void), int times){ for(int passtime = 0; passtime < times; passtime++) { // Display it X times f(); } } void loop() { displayXTimes(doFireworks, 8); displayXTimes(drawHeart, 8); } ",16205,True,4407.290766667719,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.core { import flash.display.DisplayObject; import flash.display.InteractiveObject; import flash.events.ContextMenuEvent; import flash.events.ErrorEvent; import flash.events.Event; import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.system.Capabilities; import flash.ui.ContextMenu; import flash.ui.ContextMenuItem; import flash.utils.setInterval; import mx.containers.utilityClasses.ApplicationLayout; import mx.effects.EffectManager; import mx.events.FlexEvent; import mx.managers.FocusManager; import mx.managers.IActiveWindowManager; import mx.managers.ILayoutManager; import mx.managers.ISystemManager; import mx.styles.CSSStyleDeclaration; import mx.styles.IStyleClient; import mx.utils.LoaderUtil; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched after the Application has been initialized, * processed by the LayoutManager, and attached to the display list. * * @eventType mx.events.FlexEvent.APPLICATION_COMPLETE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""applicationComplete"", type=""mx.events.FlexEvent"")] /** * Dispatched when an HTTPService call fails. * * @eventType flash.events.ErrorEvent.ERROR * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""error"", type=""flash.events.ErrorEvent"")] //-------------------------------------- // Styles //-------------------------------------- include ""../styles/metadata/ModalTransparencyStyles.as""; /** * Specifies the alpha transparency values used for the background gradient fill of the application. * You should set this to an Array of two numbers. * Elements 0 and 1 specify the start and end values for an alpha gradient. * * @default [ 1.0, 1.0 ] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""backgroundGradientAlphas"", type=""Array"", arrayType=""Number"", inherit=""no"", theme=""halo"")] /** * Specifies the colors used to tint the background gradient fill of the application. * You should set this to an Array of two uint values that specify RGB colors. * Elements 0 and 1 specify the start and end values for a color gradient. * For a solid-color background, set the same color value for elements 0 and 1. * A value of undefined means background gradient is generated * based on the backgroundColor property. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""backgroundGradientColors"", type=""Array"", arrayType=""uint"", format=""Color"", inherit=""no"", theme=""halo"")] /** * Number of pixels between the application's bottom border * and its content area. * * @default 24 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""paddingBottom"", type=""Number"", format=""Length"", inherit=""no"")] /** * Number of pixels between the application's top border * and its content area. * * @default 24 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""paddingTop"", type=""Number"", format=""Length"", inherit=""no"")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name=""direction"", kind=""property"")] [Exclude(name=""icon"", kind=""property"")] [Exclude(name=""label"", kind=""property"")] [Exclude(name=""tabIndex"", kind=""property"")] [Exclude(name=""toolTip"", kind=""property"")] [Exclude(name=""x"", kind=""property"")] [Exclude(name=""y"", kind=""property"")] //-------------------------------------- // Other metadata //-------------------------------------- /** * The frameworks must be initialized by SystemManager. * This factoryClass will be automatically subclassed by any * MXML applications that don't explicitly specify a different * factoryClass. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Frame(factoryClass=""mx.managers.SystemManager"")] [ResourceBundle(""core"")] [Alternative(replacement=""spark.components.Application"", since=""4.0"")] /** * Flex defines a default, or Application, container that lets you start * adding content to your application without explicitly defining * another container. * Flex creates this container from the <mx:Application> * tag, the first tag in an MXML application file. * While you might find it convenient to use the Application container * as the only container in your application, in most cases you explicitly * define at least one more container before you add any controls * to your application. * *

Applications support a predefined plain style that sets * a white background, left alignment, and removes all margins. * To use this style, do the following:

* *
 *    <mx:Application styleName=""plain"" />
 *  
* *

This is equivalent to setting the following style attributes:

* *
 *    backgroundColor=""0xFFFFFF""
 *    horizontalAlign=""left""
 *    paddingLeft=""0""
 *    paddingTop=""0""
 *    paddingBottom=""0""
 *    paddingRight=""0""
 *  
* * @mxml * *

The <mx:Application> tag inherits all of the tag * attributes of its superclass and adds the following tag attributes:

* *
 *  <mx:Application
 *    Properties
 *    application=""No default""
 *    controlBar=""null""
 *    frameRate=""24""
 *    historyManagementEnabled=""true|false""
 *    layout=""vertical|horizontal|absolute""
 *    pageTitle""No default""
 *    preloader=""No default""
 *    resetHistory=""false|true""
 *    scriptRecursionLimit=""1000""
 *    scriptTimeLimit=""60""
 *    usePreloader=""true|false""
 *    viewSourceURL=""""
 *    xmlns:No default=""No default""
 * 
 *    Styles 
 *    backgroundGradientAlphas=""[ 1.0, 1.0 ]""
 *    backgroundGradientColors=""undefined""
 *    horizontalAlign=""center|left|right""
 *    horizontalGap=""8""
 *    modalTransparency=""0.5""
 *    modalTransparencyBlur=""3""
 *    modalTransparencyColor=""#DDDDDD""
 *    modalTransparencyDuration=""100""
 *    paddingBottom=""24""
 *    paddingTop=""24""
 *    verticalAlign=""top|bottom|middle""
 *    verticalGap=""6""
 *  
 *    Events
 *    applicationComplete=""No default""
 *    error=""No default""
 *  />
 *  
* * @includeExample examples/SimpleApplicationExample.mxml * * @see mx.managers.CursorManager * @see mx.managers.LayoutManager * @see mx.managers.SystemManager * @see flash.events.EventDispatcher * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class Application extends LayoutContainer { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private */ mx_internal static var useProgressiveLayout:Boolean = false; //-------------------------------------------------------------------------- // // Class properties // //-------------------------------------------------------------------------- /** * A reference to the top-level application. * *

In general, there can be a hierarchy of Application objects, * because an Application can use a SWFLoader control to dynamically * load another Application. * The parentApplication property of a UIComponent can be * used to access the sub-Application in which that UIComponent lives, * and to walk up the hierarchy to the top-level Application.

* *

This property has been deprecated starting in Flex4. Note that this * property will still return applications of type mx.core.Application and * mx.core.WindowedApplication as in previous versions. Starting in Flex 4 * it will also return applications of type spark.components.Application or * spark.components.WindowedApplication.

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* * Note: here are two reasons that 'application' is typed as Object * rather than as Application. The first is for consistency with * the 'parentApplication' property of UIComponent. That property is not * typed as Application because it would make UIComponent dependent * on Application, slowing down compile times not only for SWCs * for also for MXML and AS components. Second, if it were typed * as Application, authors would not be able to access properties * and methods in the
)rawliteral""; time(&now); const char *strdate = ctime(&now); //Serial.printf(""Total space: %lluMB\\n"", SD_MMC.totalBytes() / (1024 * 1024)); //Serial.printf(""Used space: %lluMB\\n"", SD_MMC.usedBytes() / (1024 * 1024)); int tot = SD_MMC.totalBytes() / (1024 * 1024); int use = SD_MMC.usedBytes() / (1024 * 1024); //Serial.print(strlen(msg)); Serial.print("" ""); sprintf(the_page, msg, devname, devname, vernum, strdate, the_message, tot, use, recording, frames_so_far, total_frames, skipped, capture_interval, capture_interval * total_frames / 1000, quality, framesize, repeat, xspeed, gray, localip, localip, localip, localip, localip, localip); //Serial.println(strlen(the_page)); } static esp_err_t time_handler(httpd_req_t *req) { char buf[80]; size_t buf_len = httpd_req_get_url_query_len(req) + 1; if (buf_len > 1) { if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) { ESP_LOGI(TAG, ""Found URL query => %s"", buf); char param[32]; /* Get value of expected key from query string */ //Serial.println("" ... parameters""); int year = 0; int mon = 0; int day = 0; int hour = 0; int min = 0; int sec = 0; bool err = 0; if (httpd_query_key_value(buf, ""year"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 1900 && x <= 2100 ) { year = x; err = 0; Serial.println(year); }else{ err = 1; } } if (httpd_query_key_value(buf, ""mon"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 1 && x <= 12 ) { mon = x; err = 0; Serial.println(mon); }else{ err = 1; } } if (httpd_query_key_value(buf, ""day"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 1 && x <= 31 ) { day = x; err = 0; Serial.println(day); }else{ err = 1; } } if (httpd_query_key_value(buf, ""hour"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 0 && x <= 24 ) { hour = x; err = 0; Serial.println(hour); }else{ err = 1; } } if (httpd_query_key_value(buf, ""min"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 0 && x <= 60 ) { min = x; err = 0; Serial.println(min); }else{ err = 1; } } if (httpd_query_key_value(buf, ""sec"", param, sizeof(param)) == ESP_OK) { int x = atoi(param); Serial.println(x); if (x >= 0 && x <= 60 ) { sec = x; err = 0; Serial.println(sec); }else{ err = 1; } } if (err != 1) { struct tm tmGet; tmGet.tm_year = year - 1900; tmGet.tm_mon = mon; tmGet.tm_mday = day; tmGet.tm_hour = hour; tmGet.tm_min = min; tmGet.tm_sec = sec; time_t t = mktime(&tmGet); printf(""Setting time: %s"", asctime(&tmGet)); timeval tmSet = { .tv_sec = t }; settimeofday(&tmSet, NULL); timeSet = 1;//时间设置完了 } } } const char msg[] PROGMEM = R""rawliteral(Time:%s )rawliteral""; struct tm timeinfo; getLocalTime(&timeinfo); sprintf(the_page, msg, asctime(&timeinfo) ); httpd_resp_send(req, the_page, strlen(the_page)); return ESP_OK; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // static esp_err_t index_handler(httpd_req_t *req) { do_status(""Refresh Status""); httpd_resp_send(req, the_page, strlen(the_page)); return ESP_OK; } void startCameraServer() { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); httpd_uri_t index_uri = { .uri = ""/"", .method = HTTP_GET, .handler = index_handler, .user_ctx = NULL }; httpd_uri_t capture_uri = { .uri = ""/capture"", .method = HTTP_GET, .handler = capture_handler, .user_ctx = NULL }; httpd_uri_t file_stop = { .uri = ""/stop"", .method = HTTP_GET, .handler = stop_handler, .user_ctx = NULL }; httpd_uri_t file_start = { .uri = ""/start"", .method = HTTP_GET, .handler = start_handler, .user_ctx = NULL }; httpd_uri_t time_set = { .uri = ""/time"", .method = HTTP_GET, .handler = time_handler, .user_ctx = NULL }; if (httpd_start(&camera_httpd, &config) == ESP_OK) { httpd_register_uri_handler(camera_httpd, &index_uri); httpd_register_uri_handler(camera_httpd, &capture_uri); httpd_register_uri_handler(camera_httpd, &file_start); httpd_register_uri_handler(camera_httpd, &file_stop); httpd_register_uri_handler(camera_httpd, &time_set); } Serial.println(""Camera http started""); } ",16332,True,2668.4253247525185,median