code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
package com.trilead.ssh2.crypto.cipher;
/**
* BlockCipher.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: BlockCipher.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public interface BlockCipher
{
public void init(boolean forEncryption, byte[] key);
public int getBlockSize();
public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff);
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/cipher/BlockCipher.java
|
Java
|
asf20
| 406
|
package com.trilead.ssh2.crypto.cipher;
/*
This file was shamelessly taken (and modified) from the Bouncy Castle Crypto package.
Their licence file states the following:
Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle
(http://www.bouncycastle.org)
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.
*/
/**
* DESede.
*
* @author See comments in the source file
* @version $Id: DESede.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class DESede extends DES
{
private int[] key1 = null;
private int[] key2 = null;
private int[] key3 = null;
private boolean encrypt;
/**
* standard constructor.
*/
public DESede()
{
}
/**
* initialise a DES cipher.
*
* @param encrypting
* whether or not we are for encryption.
* @param key
* the parameters required to set up the cipher.
* @exception IllegalArgumentException
* if the params argument is inappropriate.
*/
public void init(boolean encrypting, byte[] key)
{
key1 = generateWorkingKey(encrypting, key, 0);
key2 = generateWorkingKey(!encrypting, key, 8);
key3 = generateWorkingKey(encrypting, key, 16);
encrypt = encrypting;
}
public String getAlgorithmName()
{
return "DESede";
}
public int getBlockSize()
{
return 8;
}
public void transformBlock(byte[] in, int inOff, byte[] out, int outOff)
{
if (key1 == null)
{
throw new IllegalStateException("DESede engine not initialised!");
}
if (encrypt)
{
desFunc(key1, in, inOff, out, outOff);
desFunc(key2, out, outOff, out, outOff);
desFunc(key3, out, outOff, out, outOff);
}
else
{
desFunc(key3, in, inOff, out, outOff);
desFunc(key2, out, outOff, out, outOff);
desFunc(key1, out, outOff, out, outOff);
}
}
public void reset()
{
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/cipher/DESede.java
|
Java
|
asf20
| 2,900
|
package com.trilead.ssh2.crypto.cipher;
/*
This file was shamelessly taken from the Bouncy Castle Crypto package.
Their licence file states the following:
Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle
(http://www.bouncycastle.org)
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.
*/
/**
* A class that provides Blowfish key encryption operations, such as encoding
* data and generating keys. All the algorithms herein are from Applied
* Cryptography and implement a simplified cryptography interface.
*
* @author See comments in the source file
* @version $Id: BlowFish.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class BlowFish implements BlockCipher
{
private final static int[] KP = { 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, 0xA4093822, 0x299F31D0,
0x082EFA98, 0xEC4E6C89, 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5,
0xB5470917, 0x9216D5D9, 0x8979FB1B },
KS0 = { 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, 0x24A19947,
0xB3916CF7, 0x0801F2E2, 0x858EFC16, 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, 0x0D95748F, 0x728EB658,
0x718BCD58, 0x82154AEE, 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, 0xC5D1B023, 0x286085F0, 0xCA417918,
0xB8DB38EF, 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60,
0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, 0xA15486AF,
0x7C72E993, 0xB3EE1411, 0x636FBC2A, 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, 0xAFD6BA33, 0x6C24CF5C,
0x7A325381, 0x28958677, 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, 0x61D809CC, 0xFB21A991, 0x487CAC60,
0x5DEC8032, 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239,
0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, 0x6A51A0D2,
0xD8542F68, 0x960FA728, 0xAB5133A3, 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, 0xA1F1651D, 0x39AF0176,
0x66CA593E, 0x82430E88, 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, 0xE06F75D8, 0x85C12073, 0x401A449F,
0x56C16AA6, 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B,
0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, 0xC1A94FB6,
0x409F60C4, 0x5E5C9EC2, 0x196A2463, 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, 0x6DFC511F, 0x9B30952C,
0xCC814544, 0xAF5EBD09, 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, 0xC0CBA857, 0x45C8740F, 0xD20B5F39,
0xB9D3FBDB, 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8,
0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, 0x9E5C57BB,
0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, 0x695B27B0, 0xBBCA58C8,
0xE1FFA35D, 0xB8F011A0, 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, 0x9A53E479, 0xB6F84565, 0xD28E49BC,
0x4BFB9790, 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4,
0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, 0x8FF6E2FB,
0xF2122B64, 0x8888B812, 0x900DF01C, 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, 0x2F2F2218, 0xBE0E1777,
0xEA752DFE, 0x8B021FA1, 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81,
0xD2ADA8D9, 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF,
0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, 0x2464369B,
0xF009B91E, 0x5563911D, 0x59DFA6AA, 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, 0x83260376, 0x6295CFA9,
0x11C81968, 0x4E734A41, 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, 0xD60F573F, 0xBC9BC6E4, 0x2B60A476,
0x81E67400, 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664,
0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A },
KS1 = { 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, 0xECAA8C71,
0x699A17FF, 0x5664526C, 0xC2B19EE1, 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, 0x3F54989A, 0x5B429D65,
0x6B8FE4D6, 0x99F73FD6, 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, 0x4CDD2086, 0x8470EB26, 0x6382E9C6,
0x021ECC5E, 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737,
0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, 0xAE0CF51A,
0x3CB574B2, 0x25837A58, 0xDC0921BD, 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, 0x3AE5E581, 0x37C2DADC,
0xC8B57634, 0x9AF3DDA7, 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1,
0x183EB331, 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF,
0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, 0x7A584718,
0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, 0xEF1C1847, 0x3215D908,
0xDD433B37, 0x24C2BA16, 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, 0x71DFF89E, 0x10314E55, 0x81AC77D6,
0x5F11199B, 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E,
0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, 0x803E89D6,
0x5266C825, 0x2E4CC978, 0x9C10B36A, 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, 0xF2F74EA7, 0x361D2B3D,
0x1939260F, 0x19C27960, 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, 0xE3BC4595, 0xA67BC883, 0xB17F37D1,
0x018CFF28, 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84,
0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, 0xB5735C90,
0x4C70A239, 0xD59E9E0B, 0xCBAADE14, 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, 0x648B1EAF, 0x19BDF0CA,
0xA02369B9, 0x655ABB50, 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, 0x9B540B19, 0x875FA099, 0x95F7997E,
0x623D7DA8, 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99,
0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, 0x58EBF2EF,
0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, 0x45EEE2B6, 0xA3AAABEA,
0xDB6C4F15, 0xFACB4FD0, 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, 0xD81E799E, 0x86854DC7, 0xE44B476A,
0x3D816250, 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285,
0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, 0x3372F092,
0x8D937E41, 0xD65FECF1, 0x6C223BDB, 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, 0xA6078084, 0x19F8509E,
0xE8EFD855, 0x61D99735, 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, 0x9E447A2E, 0xC3453484, 0xFDD56705,
0x0E1E9EC9, 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20,
0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 },
KS2 = { 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, 0xD4082471,
0x3320F46A, 0x43B7D4B7, 0x500061AF, 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, 0x4D95FC1D, 0x96B591AF,
0x70F4DDD3, 0x66A02F45, 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, 0x96EB27B3, 0x55FD3941, 0xDA2547E6,
0xABCA0A9A, 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE,
0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, 0x20FE9E35,
0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, 0x3A6EFA74, 0xDD5B4332,
0x6841E7F7, 0xCA7820FB, 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, 0x55533A3A, 0x20838D87, 0xFE6BA9B7,
0xD096954B, 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C,
0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, 0x07F9C9EE,
0x41041F0F, 0x404779A4, 0x5D886E17, 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, 0x257B7834, 0x602A9C60,
0xDFF8E8A3, 0x1F636C1B, 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, 0x6B2395E0, 0x333E92E1, 0x3B240B62,
0xEEBEB922, 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0,
0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, 0xA812DC60,
0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, 0xF1290DC7, 0xCC00FFA3,
0xB5390F92, 0x690FED0B, 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, 0xBB132F88, 0x515BAD24, 0x7B9479BF,
0x763BD6EB, 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C,
0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, 0x44421659,
0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, 0x9DBC8057, 0xF0F7C086,
0x60787BF8, 0x6003604D, 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, 0x83426B33, 0xF01EAB71, 0xB0804187,
0x3C005E5F, 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2,
0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, 0x466E598E,
0x20B45770, 0x8CD55591, 0xC902DE4C, 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, 0xB77F19B6, 0xE0A9DC09,
0x662D09A1, 0xC4324633, 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F,
0x2868F169, 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027,
0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, 0x11E69ED7,
0x2338EA63, 0x53C2DD94, 0xC2C21634, 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, 0x6F05E409, 0x4B7C0188,
0x39720A3D, 0x7C927C24, 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, 0xED545578, 0x08FCA5B5, 0xD83D7CD3,
0x4DAD0FC4, 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837,
0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 },
KS3 = { 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, 0xD5118E9D,
0xBF0F7315, 0xD62D1C7E, 0xC700C47B, 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, 0x5748AB2F, 0xBC946E79,
0xC6A376D2, 0x6549C2C8, 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, 0x2939BBDB, 0xA9BA4650, 0xAC9526E8,
0xBE5EE304, 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4,
0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, 0xC72FEFD3,
0xF752F7DA, 0x3F046F69, 0x77FA0A59, 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, 0xE990FD5A, 0x9E34D797,
0x2CF0B7D9, 0x022B8B51, 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472,
0x5A88F54C, 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28,
0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, 0xC3EB9E15,
0x3C9057A2, 0x97271AEC, 0xA93A072A, 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, 0x7533D928, 0xB155FDF5,
0x03563482, 0x8ABA3CBB, 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, 0x4DE81751, 0x3830DC8E, 0x379D5862,
0x9320F991, 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680,
0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, 0x5BBEF7DD,
0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, 0x72EACEA8, 0xFA6484BB,
0x8D6612AE, 0xBF3C6F47, 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, 0x740E0D8D, 0xE75B1357, 0xF8721671,
0xAF537D5D, 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048,
0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, 0xA08839E1,
0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, 0x1A908749, 0xD44FBD9A,
0xD0DADECB, 0xD50ADA38, 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF,
0x27D9459C, 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1,
0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, 0x9F1F9532,
0xE0D392DF, 0xD3A0342B, 0x8971F21E, 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, 0xDF359F8D, 0x9B992F2E,
0xE60B6F47, 0x0FE3F11D, 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, 0x1618B166, 0xFD2C1D05, 0x848FD2C5,
0xF6FB2299, 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC,
0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, 0xC9AA53FD,
0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, 0x53113EC0, 0x1640E3D3,
0x38ABBD60, 0x2547ADF0, 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0,
0x4CF9AA7E, 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F,
0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 };
// ====================================
// Useful constants
// ====================================
private static final int ROUNDS = 16;
private static final int BLOCK_SIZE = 8; // bytes = 64 bits
private static final int SBOX_SK = 256;
private static final int P_SZ = ROUNDS + 2;
private final int[] S0, S1, S2, S3; // the s-boxes
private final int[] P; // the p-array
private boolean doEncrypt = false;
private byte[] workingKey = null;
public BlowFish()
{
S0 = new int[SBOX_SK];
S1 = new int[SBOX_SK];
S2 = new int[SBOX_SK];
S3 = new int[SBOX_SK];
P = new int[P_SZ];
}
/**
* initialise a Blowfish cipher.
*
* @param encrypting
* whether or not we are for encryption.
* @param key
* the key required to set up the cipher.
* @exception IllegalArgumentException
* if the params argument is inappropriate.
*/
public void init(boolean encrypting, byte[] key)
{
this.doEncrypt = encrypting;
this.workingKey = key;
setKey(this.workingKey);
}
public String getAlgorithmName()
{
return "Blowfish";
}
public final void transformBlock(byte[] in, int inOff, byte[] out, int outOff)
{
if (workingKey == null)
{
throw new IllegalStateException("Blowfish not initialised");
}
if (doEncrypt)
{
encryptBlock(in, inOff, out, outOff);
}
else
{
decryptBlock(in, inOff, out, outOff);
}
}
public void reset()
{
}
public int getBlockSize()
{
return BLOCK_SIZE;
}
// ==================================
// Private Implementation
// ==================================
private int F(int x)
{
return (((S0[(x >>> 24)] + S1[(x >>> 16) & 0xff]) ^ S2[(x >>> 8) & 0xff]) + S3[x & 0xff]);
}
/**
* apply the encryption cycle to each value pair in the table.
*/
private void processTable(int xl, int xr, int[] table)
{
int size = table.length;
for (int s = 0; s < size; s += 2)
{
xl ^= P[0];
for (int i = 1; i < ROUNDS; i += 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i + 1];
}
xr ^= P[ROUNDS + 1];
table[s] = xr;
table[s + 1] = xl;
xr = xl; // end of cycle swap
xl = table[s];
}
}
private void setKey(byte[] key)
{
/*
* - comments are from _Applied Crypto_, Schneier, p338 please be
* careful comparing the two, AC numbers the arrays from 1, the enclosed
* code from 0.
*
* (1) Initialise the S-boxes and the P-array, with a fixed string This
* string contains the hexadecimal digits of pi (3.141...)
*/
System.arraycopy(KS0, 0, S0, 0, SBOX_SK);
System.arraycopy(KS1, 0, S1, 0, SBOX_SK);
System.arraycopy(KS2, 0, S2, 0, SBOX_SK);
System.arraycopy(KS3, 0, S3, 0, SBOX_SK);
System.arraycopy(KP, 0, P, 0, P_SZ);
/*
* (2) Now, XOR P[0] with the first 32 bits of the key, XOR P[1] with
* the second 32-bits of the key, and so on for all bits of the key (up
* to P[17]). Repeatedly cycle through the key bits until the entire
* P-array has been XOR-ed with the key bits
*/
int keyLength = key.length;
int keyIndex = 0;
for (int i = 0; i < P_SZ; i++)
{
// get the 32 bits of the key, in 4 * 8 bit chunks
int data = 0x0000000;
for (int j = 0; j < 4; j++)
{
// create a 32 bit block
data = (data << 8) | (key[keyIndex++] & 0xff);
// wrap when we get to the end of the key
if (keyIndex >= keyLength)
{
keyIndex = 0;
}
}
// XOR the newly created 32 bit chunk onto the P-array
P[i] ^= data;
}
/*
* (3) Encrypt the all-zero string with the Blowfish algorithm, using
* the subkeys described in (1) and (2)
*
* (4) Replace P1 and P2 with the output of step (3)
*
* (5) Encrypt the output of step(3) using the Blowfish algorithm, with
* the modified subkeys.
*
* (6) Replace P3 and P4 with the output of step (5)
*
* (7) Continue the process, replacing all elements of the P-array and
* then all four S-boxes in order, with the output of the continuously
* changing Blowfish algorithm
*/
processTable(0, 0, P);
processTable(P[P_SZ - 2], P[P_SZ - 1], S0);
processTable(S0[SBOX_SK - 2], S0[SBOX_SK - 1], S1);
processTable(S1[SBOX_SK - 2], S1[SBOX_SK - 1], S2);
processTable(S2[SBOX_SK - 2], S2[SBOX_SK - 1], S3);
}
/**
* Encrypt the given input starting at the given offset and place the result
* in the provided buffer starting at the given offset. The input will be an
* exact multiple of our blocksize.
*/
private void encryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex)
{
int xl = BytesTo32bits(src, srcIndex);
int xr = BytesTo32bits(src, srcIndex + 4);
xl ^= P[0];
for (int i = 1; i < ROUNDS; i += 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i + 1];
}
xr ^= P[ROUNDS + 1];
Bits32ToBytes(xr, dst, dstIndex);
Bits32ToBytes(xl, dst, dstIndex + 4);
}
/**
* Decrypt the given input starting at the given offset and place the result
* in the provided buffer starting at the given offset. The input will be an
* exact multiple of our blocksize.
*/
private void decryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex)
{
int xl = BytesTo32bits(src, srcIndex);
int xr = BytesTo32bits(src, srcIndex + 4);
xl ^= P[ROUNDS + 1];
for (int i = ROUNDS; i > 0; i -= 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i - 1];
}
xr ^= P[0];
Bits32ToBytes(xr, dst, dstIndex);
Bits32ToBytes(xl, dst, dstIndex + 4);
}
private int BytesTo32bits(byte[] b, int i)
{
return ((b[i] & 0xff) << 24) | ((b[i + 1] & 0xff) << 16) | ((b[i + 2] & 0xff) << 8) | ((b[i + 3] & 0xff));
}
private void Bits32ToBytes(int in, byte[] b, int offset)
{
b[offset + 3] = (byte) in;
b[offset + 2] = (byte) (in >> 8);
b[offset + 1] = (byte) (in >> 16);
b[offset] = (byte) (in >> 24);
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/cipher/BlowFish.java
|
Java
|
asf20
| 20,816
|
package com.trilead.ssh2.crypto.cipher;
/**
* NullCipher.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: NullCipher.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class NullCipher implements BlockCipher
{
private int blockSize = 8;
public NullCipher()
{
}
public NullCipher(int blockSize)
{
this.blockSize = blockSize;
}
public void init(boolean forEncryption, byte[] key)
{
}
public int getBlockSize()
{
return blockSize;
}
public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
System.arraycopy(src, srcoff, dst, dstoff, blockSize);
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/cipher/NullCipher.java
|
Java
|
asf20
| 663
|
package com.trilead.ssh2.crypto.digest;
import java.math.BigInteger;
/**
* HashForSSH2Types.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HashForSSH2Types.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class HashForSSH2Types
{
Digest md;
public HashForSSH2Types(Digest md)
{
this.md = md;
}
public HashForSSH2Types(String type)
{
if (type.equals("SHA1"))
{
md = new SHA1();
}
else if (type.equals("MD5"))
{
md = new MD5();
}
else
throw new IllegalArgumentException("Unknown algorithm " + type);
}
public void updateByte(byte b)
{
/* HACK - to test it with J2ME */
byte[] tmp = new byte[1];
tmp[0] = b;
md.update(tmp);
}
public void updateBytes(byte[] b)
{
md.update(b);
}
public void updateUINT32(int v)
{
md.update((byte) (v >> 24));
md.update((byte) (v >> 16));
md.update((byte) (v >> 8));
md.update((byte) (v));
}
public void updateByteString(byte[] b)
{
updateUINT32(b.length);
updateBytes(b);
}
public void updateBigInt(BigInteger b)
{
updateByteString(b.toByteArray());
}
public void reset()
{
md.reset();
}
public int getDigestLength()
{
return md.getDigestLength();
}
public byte[] getDigest()
{
byte[] tmp = new byte[md.getDigestLength()];
getDigest(tmp);
return tmp;
}
public void getDigest(byte[] out)
{
getDigest(out, 0);
}
public void getDigest(byte[] out, int off)
{
md.digest(out, off);
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/digest/HashForSSH2Types.java
|
Java
|
asf20
| 1,553
|
package com.trilead.ssh2.crypto.digest;
/**
* MAC.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: MAC.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public final class MAC
{
Digest mac;
int size;
public final static String[] getMacList()
{
/* Higher Priority First */
return new String[] { "hmac-sha1-96", "hmac-sha1", "hmac-md5-96", "hmac-md5" };
}
public final static void checkMacList(String[] macs)
{
for (int i = 0; i < macs.length; i++)
getKeyLen(macs[i]);
}
public final static int getKeyLen(String type)
{
if (type.equals("hmac-sha1"))
return 20;
if (type.equals("hmac-sha1-96"))
return 20;
if (type.equals("hmac-md5"))
return 16;
if (type.equals("hmac-md5-96"))
return 16;
throw new IllegalArgumentException("Unkown algorithm " + type);
}
public MAC(String type, byte[] key)
{
if (type.equals("hmac-sha1"))
{
mac = new HMAC(new SHA1(), key, 20);
}
else if (type.equals("hmac-sha1-96"))
{
mac = new HMAC(new SHA1(), key, 12);
}
else if (type.equals("hmac-md5"))
{
mac = new HMAC(new MD5(), key, 16);
}
else if (type.equals("hmac-md5-96"))
{
mac = new HMAC(new MD5(), key, 12);
}
else
throw new IllegalArgumentException("Unkown algorithm " + type);
size = mac.getDigestLength();
}
public final void initMac(int seq)
{
mac.reset();
mac.update((byte) (seq >> 24));
mac.update((byte) (seq >> 16));
mac.update((byte) (seq >> 8));
mac.update((byte) (seq));
}
public final void update(byte[] packetdata, int off, int len)
{
mac.update(packetdata, off, len);
}
public final void getMac(byte[] out, int off)
{
mac.digest(out, off);
}
public final int size()
{
return size;
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/digest/MAC.java
|
Java
|
asf20
| 1,822
|
package com.trilead.ssh2.crypto.digest;
/**
* HMAC.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HMAC.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public final class HMAC implements Digest
{
Digest md;
byte[] k_xor_ipad;
byte[] k_xor_opad;
byte[] tmp;
int size;
public HMAC(Digest md, byte[] key, int size)
{
this.md = md;
this.size = size;
tmp = new byte[md.getDigestLength()];
final int BLOCKSIZE = 64;
k_xor_ipad = new byte[BLOCKSIZE];
k_xor_opad = new byte[BLOCKSIZE];
if (key.length > BLOCKSIZE)
{
md.reset();
md.update(key);
md.digest(tmp);
key = tmp;
}
System.arraycopy(key, 0, k_xor_ipad, 0, key.length);
System.arraycopy(key, 0, k_xor_opad, 0, key.length);
for (int i = 0; i < BLOCKSIZE; i++)
{
k_xor_ipad[i] ^= 0x36;
k_xor_opad[i] ^= 0x5C;
}
md.update(k_xor_ipad);
}
public final int getDigestLength()
{
return size;
}
public final void update(byte b)
{
md.update(b);
}
public final void update(byte[] b)
{
md.update(b);
}
public final void update(byte[] b, int off, int len)
{
md.update(b, off, len);
}
public final void reset()
{
md.reset();
md.update(k_xor_ipad);
}
public final void digest(byte[] out)
{
digest(out, 0);
}
public final void digest(byte[] out, int off)
{
md.digest(tmp);
md.update(k_xor_opad);
md.update(tmp);
md.digest(tmp);
System.arraycopy(tmp, 0, out, off, size);
md.update(k_xor_ipad);
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/digest/HMAC.java
|
Java
|
asf20
| 1,578
|
package com.trilead.ssh2.crypto.digest;
/**
* MD5. Based on the example code in RFC 1321. Optimized (...a little).
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: MD5.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
/*
* The following disclaimer has been copied from RFC 1321:
*
* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights
* reserved.
*
* License to copy and use this software is granted provided that it is
* identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in
* all material mentioning or referencing this software or this function.
*
* License is also granted to make and use derivative works provided that such
* works are identified as "derived from the RSA Data Security, Inc. MD5
* Message-Digest Algorithm" in all material mentioning or referencing the
* derived work.
*
* RSA Data Security, Inc. makes no representations concerning either the
* merchantability of this software or the suitability of this software for any
* particular purpose. It is provided "as is" without express or implied
* warranty of any kind.
*
* These notices must be retained in any copies of any part of this
* documentation and/or software.
*
*/
public final class MD5 implements Digest
{
private int state0, state1, state2, state3;
private long count;
private final byte[] block = new byte[64];
private final int x[] = new int[16];
private static final byte[] padding = new byte[] { (byte) 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
public MD5()
{
reset();
}
private static final int FF(int a, int b, int c, int d, int x, int s, int ac)
{
a += ((b & c) | ((~b) & d)) + x + ac;
return ((a << s) | (a >>> (32 - s))) + b;
}
private static final int GG(int a, int b, int c, int d, int x, int s, int ac)
{
a += ((b & d) | (c & (~d))) + x + ac;
return ((a << s) | (a >>> (32 - s))) + b;
}
private static final int HH(int a, int b, int c, int d, int x, int s, int ac)
{
a += (b ^ c ^ d) + x + ac;
return ((a << s) | (a >>> (32 - s))) + b;
}
private static final int II(int a, int b, int c, int d, int x, int s, int ac)
{
a += (c ^ (b | (~d))) + x + ac;
return ((a << s) | (a >>> (32 - s))) + b;
}
private static final void encode(byte[] dst, int dstoff, int word)
{
dst[dstoff] = (byte) (word);
dst[dstoff + 1] = (byte) (word >> 8);
dst[dstoff + 2] = (byte) (word >> 16);
dst[dstoff + 3] = (byte) (word >> 24);
}
private final void transform(byte[] src, int pos)
{
int a = state0;
int b = state1;
int c = state2;
int d = state3;
for (int i = 0; i < 16; i++, pos += 4)
{
x[i] = (src[pos] & 0xff) | ((src[pos + 1] & 0xff) << 8) | ((src[pos + 2] & 0xff) << 16)
| ((src[pos + 3] & 0xff) << 24);
}
/* Round 1 */
a = FF(a, b, c, d, x[0], 7, 0xd76aa478); /* 1 */
d = FF(d, a, b, c, x[1], 12, 0xe8c7b756); /* 2 */
c = FF(c, d, a, b, x[2], 17, 0x242070db); /* 3 */
b = FF(b, c, d, a, x[3], 22, 0xc1bdceee); /* 4 */
a = FF(a, b, c, d, x[4], 7, 0xf57c0faf); /* 5 */
d = FF(d, a, b, c, x[5], 12, 0x4787c62a); /* 6 */
c = FF(c, d, a, b, x[6], 17, 0xa8304613); /* 7 */
b = FF(b, c, d, a, x[7], 22, 0xfd469501); /* 8 */
a = FF(a, b, c, d, x[8], 7, 0x698098d8); /* 9 */
d = FF(d, a, b, c, x[9], 12, 0x8b44f7af); /* 10 */
c = FF(c, d, a, b, x[10], 17, 0xffff5bb1); /* 11 */
b = FF(b, c, d, a, x[11], 22, 0x895cd7be); /* 12 */
a = FF(a, b, c, d, x[12], 7, 0x6b901122); /* 13 */
d = FF(d, a, b, c, x[13], 12, 0xfd987193); /* 14 */
c = FF(c, d, a, b, x[14], 17, 0xa679438e); /* 15 */
b = FF(b, c, d, a, x[15], 22, 0x49b40821); /* 16 */
/* Round 2 */
a = GG(a, b, c, d, x[1], 5, 0xf61e2562); /* 17 */
d = GG(d, a, b, c, x[6], 9, 0xc040b340); /* 18 */
c = GG(c, d, a, b, x[11], 14, 0x265e5a51); /* 19 */
b = GG(b, c, d, a, x[0], 20, 0xe9b6c7aa); /* 20 */
a = GG(a, b, c, d, x[5], 5, 0xd62f105d); /* 21 */
d = GG(d, a, b, c, x[10], 9, 0x2441453); /* 22 */
c = GG(c, d, a, b, x[15], 14, 0xd8a1e681); /* 23 */
b = GG(b, c, d, a, x[4], 20, 0xe7d3fbc8); /* 24 */
a = GG(a, b, c, d, x[9], 5, 0x21e1cde6); /* 25 */
d = GG(d, a, b, c, x[14], 9, 0xc33707d6); /* 26 */
c = GG(c, d, a, b, x[3], 14, 0xf4d50d87); /* 27 */
b = GG(b, c, d, a, x[8], 20, 0x455a14ed); /* 28 */
a = GG(a, b, c, d, x[13], 5, 0xa9e3e905); /* 29 */
d = GG(d, a, b, c, x[2], 9, 0xfcefa3f8); /* 30 */
c = GG(c, d, a, b, x[7], 14, 0x676f02d9); /* 31 */
b = GG(b, c, d, a, x[12], 20, 0x8d2a4c8a); /* 32 */
/* Round 3 */
a = HH(a, b, c, d, x[5], 4, 0xfffa3942); /* 33 */
d = HH(d, a, b, c, x[8], 11, 0x8771f681); /* 34 */
c = HH(c, d, a, b, x[11], 16, 0x6d9d6122); /* 35 */
b = HH(b, c, d, a, x[14], 23, 0xfde5380c); /* 36 */
a = HH(a, b, c, d, x[1], 4, 0xa4beea44); /* 37 */
d = HH(d, a, b, c, x[4], 11, 0x4bdecfa9); /* 38 */
c = HH(c, d, a, b, x[7], 16, 0xf6bb4b60); /* 39 */
b = HH(b, c, d, a, x[10], 23, 0xbebfbc70); /* 40 */
a = HH(a, b, c, d, x[13], 4, 0x289b7ec6); /* 41 */
d = HH(d, a, b, c, x[0], 11, 0xeaa127fa); /* 42 */
c = HH(c, d, a, b, x[3], 16, 0xd4ef3085); /* 43 */
b = HH(b, c, d, a, x[6], 23, 0x4881d05); /* 44 */
a = HH(a, b, c, d, x[9], 4, 0xd9d4d039); /* 45 */
d = HH(d, a, b, c, x[12], 11, 0xe6db99e5); /* 46 */
c = HH(c, d, a, b, x[15], 16, 0x1fa27cf8); /* 47 */
b = HH(b, c, d, a, x[2], 23, 0xc4ac5665); /* 48 */
/* Round 4 */
a = II(a, b, c, d, x[0], 6, 0xf4292244); /* 49 */
d = II(d, a, b, c, x[7], 10, 0x432aff97); /* 50 */
c = II(c, d, a, b, x[14], 15, 0xab9423a7); /* 51 */
b = II(b, c, d, a, x[5], 21, 0xfc93a039); /* 52 */
a = II(a, b, c, d, x[12], 6, 0x655b59c3); /* 53 */
d = II(d, a, b, c, x[3], 10, 0x8f0ccc92); /* 54 */
c = II(c, d, a, b, x[10], 15, 0xffeff47d); /* 55 */
b = II(b, c, d, a, x[1], 21, 0x85845dd1); /* 56 */
a = II(a, b, c, d, x[8], 6, 0x6fa87e4f); /* 57 */
d = II(d, a, b, c, x[15], 10, 0xfe2ce6e0); /* 58 */
c = II(c, d, a, b, x[6], 15, 0xa3014314); /* 59 */
b = II(b, c, d, a, x[13], 21, 0x4e0811a1); /* 60 */
a = II(a, b, c, d, x[4], 6, 0xf7537e82); /* 61 */
d = II(d, a, b, c, x[11], 10, 0xbd3af235); /* 62 */
c = II(c, d, a, b, x[2], 15, 0x2ad7d2bb); /* 63 */
b = II(b, c, d, a, x[9], 21, 0xeb86d391); /* 64 */
state0 += a;
state1 += b;
state2 += c;
state3 += d;
}
public final void reset()
{
count = 0;
state0 = 0x67452301;
state1 = 0xefcdab89;
state2 = 0x98badcfe;
state3 = 0x10325476;
/* Clear traces in memory... */
for (int i = 0; i < 16; i++)
x[i] = 0;
}
public final void update(byte b)
{
final int space = 64 - ((int) (count & 0x3f));
count++;
block[64 - space] = b;
if (space == 1)
transform(block, 0);
}
public final void update(byte[] buff, int pos, int len)
{
int space = 64 - ((int) (count & 0x3f));
count += len;
while (len > 0)
{
if (len < space)
{
System.arraycopy(buff, pos, block, 64 - space, len);
break;
}
if (space == 64)
{
transform(buff, pos);
}
else
{
System.arraycopy(buff, pos, block, 64 - space, space);
transform(block, 0);
}
pos += space;
len -= space;
space = 64;
}
}
public final void update(byte[] b)
{
update(b, 0, b.length);
}
public final void digest(byte[] dst, int pos)
{
byte[] bits = new byte[8];
encode(bits, 0, (int) (count << 3));
encode(bits, 4, (int) (count >> 29));
int idx = (int) count & 0x3f;
int padLen = (idx < 56) ? (56 - idx) : (120 - idx);
update(padding, 0, padLen);
update(bits, 0, 8);
encode(dst, pos, state0);
encode(dst, pos + 4, state1);
encode(dst, pos + 8, state2);
encode(dst, pos + 12, state3);
reset();
}
public final void digest(byte[] dst)
{
digest(dst, 0);
}
public final int getDigestLength()
{
return 16;
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/digest/MD5.java
|
Java
|
asf20
| 8,195
|
package com.trilead.ssh2.crypto.digest;
/**
* SHA-1 implementation based on FIPS PUB 180-1.
* Highly optimized.
* <p>
* (http://www.itl.nist.gov/fipspubs/fip180-1.htm)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SHA1.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public final class SHA1 implements Digest
{
private int H0, H1, H2, H3, H4;
private final int[] w = new int[80];
private int currentPos;
private long currentLen;
public SHA1()
{
reset();
}
public final int getDigestLength()
{
return 20;
}
public final void reset()
{
H0 = 0x67452301;
H1 = 0xEFCDAB89;
H2 = 0x98BADCFE;
H3 = 0x10325476;
H4 = 0xC3D2E1F0;
currentPos = 0;
currentLen = 0;
/* In case of complete paranoia, we should also wipe out the
* information contained in the w[] array */
}
public final void update(byte b[])
{
update(b, 0, b.length);
}
public final void update(byte b[], int off, int len)
{
if (len >= 4)
{
int idx = currentPos >> 2;
switch (currentPos & 3)
{
case 0:
w[idx] = (((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff));
len -= 4;
currentPos += 4;
currentLen += 32;
if (currentPos == 64)
{
perform();
currentPos = 0;
}
break;
case 1:
w[idx] = (w[idx] << 24) | (((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff));
len -= 3;
currentPos += 3;
currentLen += 24;
if (currentPos == 64)
{
perform();
currentPos = 0;
}
break;
case 2:
w[idx] = (w[idx] << 16) | (((b[off++] & 0xff) << 8) | (b[off++] & 0xff));
len -= 2;
currentPos += 2;
currentLen += 16;
if (currentPos == 64)
{
perform();
currentPos = 0;
}
break;
case 3:
w[idx] = (w[idx] << 8) | (b[off++] & 0xff);
len--;
currentPos++;
currentLen += 8;
if (currentPos == 64)
{
perform();
currentPos = 0;
}
break;
}
/* Now currentPos is a multiple of 4 - this is the place to be...*/
while (len >= 8)
{
w[currentPos >> 2] = ((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8)
| (b[off++] & 0xff);
currentPos += 4;
if (currentPos == 64)
{
perform();
currentPos = 0;
}
w[currentPos >> 2] = ((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8)
| (b[off++] & 0xff);
currentPos += 4;
if (currentPos == 64)
{
perform();
currentPos = 0;
}
currentLen += 64;
len -= 8;
}
while (len < 0) //(len >= 4)
{
w[currentPos >> 2] = ((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8)
| (b[off++] & 0xff);
len -= 4;
currentPos += 4;
currentLen += 32;
if (currentPos == 64)
{
perform();
currentPos = 0;
}
}
}
/* Remaining bytes (1-3) */
while (len > 0)
{
/* Here is room for further improvements */
int idx = currentPos >> 2;
w[idx] = (w[idx] << 8) | (b[off++] & 0xff);
currentLen += 8;
currentPos++;
if (currentPos == 64)
{
perform();
currentPos = 0;
}
len--;
}
}
public final void update(byte b)
{
int idx = currentPos >> 2;
w[idx] = (w[idx] << 8) | (b & 0xff);
currentLen += 8;
currentPos++;
if (currentPos == 64)
{
perform();
currentPos = 0;
}
}
private final void putInt(byte[] b, int pos, int val)
{
b[pos] = (byte) (val >> 24);
b[pos + 1] = (byte) (val >> 16);
b[pos + 2] = (byte) (val >> 8);
b[pos + 3] = (byte) val;
}
public final void digest(byte[] out)
{
digest(out, 0);
}
public final void digest(byte[] out, int off)
{
/* Pad with a '1' and 7-31 zero bits... */
int idx = currentPos >> 2;
w[idx] = ((w[idx] << 8) | (0x80)) << ((3 - (currentPos & 3)) << 3);
currentPos = (currentPos & ~3) + 4;
if (currentPos == 64)
{
currentPos = 0;
perform();
}
else if (currentPos == 60)
{
currentPos = 0;
w[15] = 0;
perform();
}
/* Now currentPos is a multiple of 4 and we can do the remaining
* padding much more efficiently, furthermore we are sure
* that currentPos <= 56.
*/
for (int i = currentPos >> 2; i < 14; i++)
w[i] = 0;
w[14] = (int) (currentLen >> 32);
w[15] = (int) currentLen;
perform();
putInt(out, off, H0);
putInt(out, off + 4, H1);
putInt(out, off + 8, H2);
putInt(out, off + 12, H3);
putInt(out, off + 16, H4);
reset();
}
private final void perform()
{
for (int t = 16; t < 80; t++)
{
int x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
w[t] = ((x << 1) | (x >>> 31));
}
int A = H0;
int B = H1;
int C = H2;
int D = H3;
int E = H4;
/* Here we use variable substitution and loop unrolling
*
* === Original step:
*
* T = s5(A) + f(B,C,D) + E + w[0] + K;
* E = D; D = C; C = s30(B); B = A; A = T;
*
* === Rewritten step:
*
* T = s5(A + f(B,C,D) + E + w[0] + K;
* B = s30(B);
* E = D; D = C; C = B; B = A; A = T;
*
* === Let's rewrite things, introducing new variables:
*
* E0 = E; D0 = D; C0 = C; B0 = B; A0 = A;
*
* T = s5(A0) + f(B0,C0,D0) + E0 + w[0] + K;
* B0 = s30(B0);
* E1 = D0; D1 = C0; C1 = B0; B1 = A0; A1 = T;
*
* T = s5(A1) + f(B1,C1,D1) + E1 + w[1] + K;
* B1 = s30(B1);
* E2 = D1; D2 = C1; C2 = B1; B2 = A1; A2 = T;
*
* E = E2; D = E2; C = C2; B = B2; A = A2;
*
* === No need for 'T', we can write into 'Ex' instead since
* after the calculation of 'T' nobody is interested
* in 'Ex' anymore.
*
* E0 = E; D0 = D; C0 = C; B0 = B; A0 = A;
*
* E0 = E0 + s5(A0) + f(B0,C0,D0) + w[0] + K;
* B0 = s30(B0);
* E1 = D0; D1 = C0; C1 = B0; B1 = A0; A1 = E0;
*
* E1 = E1 + s5(A1) + f(B1,C1,D1) + w[1] + K;
* B1 = s30(B1);
* E2 = D1; D2 = C1; C2 = B1; B2 = A1; A2 = E1;
*
* E = Ex; D = Ex; C = Cx; B = Bx; A = Ax;
*
* === Further optimization: get rid of the swap operations
* Idea: instead of swapping the variables, swap the names of
* the used variables in the next step:
*
* E0 = E; D0 = d; C0 = C; B0 = B; A0 = A;
*
* E0 = E0 + s5(A0) + f(B0,C0,D0) + w[0] + K;
* B0 = s30(B0);
* // E1 = D0; D1 = C0; C1 = B0; B1 = A0; A1 = E0;
*
* D0 = D0 + s5(E0) + f(A0,B0,C0) + w[1] + K;
* A0 = s30(A0);
* E2 = C0; D2 = B0; C2 = A0; B2 = E0; A2 = D0;
*
* E = E2; D = D2; C = C2; B = B2; A = A2;
*
* === OK, let's do this several times, also, directly
* use A (instead of A0) and B,C,D,E.
*
* E = E + s5(A) + f(B,C,D) + w[0] + K;
* B = s30(B);
* // E1 = D; D1 = C; C1 = B; B1 = A; A1 = E;
*
* D = D + s5(E) + f(A,B,C) + w[1] + K;
* A = s30(A);
* // E2 = C; D2 = B; C2 = A; B2 = E; A2 = D;
*
* C = C + s5(D) + f(E,A,B) + w[2] + K;
* E = s30(E);
* // E3 = B; D3 = A; C3 = E; B3 = D; A3 = C;
*
* B = B + s5(C) + f(D,E,A) + w[3] + K;
* D = s30(D);
* // E4 = A; D4 = E; C4 = D; B4 = C; A4 = B;
*
* A = A + s5(B) + f(C,D,E) + w[4] + K;
* C = s30(C);
* // E5 = E; D5 = D; C5 = C; B5 = B; A5 = A;
*
* //E = E5; D = D5; C = C5; B = B5; A = A5;
*
* === Very nice, after 5 steps each variable
* has the same contents as after 5 steps with
* the original algorithm!
*
* We therefore can easily unroll each interval,
* as the number of steps in each interval is a
* multiple of 5 (20 steps per interval).
*/
E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[0] + 0x5A827999;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[1] + 0x5A827999;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[2] + 0x5A827999;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[3] + 0x5A827999;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[4] + 0x5A827999;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[5] + 0x5A827999;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[6] + 0x5A827999;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[7] + 0x5A827999;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[8] + 0x5A827999;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[9] + 0x5A827999;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[10] + 0x5A827999;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[11] + 0x5A827999;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[12] + 0x5A827999;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[13] + 0x5A827999;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[14] + 0x5A827999;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[15] + 0x5A827999;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[16] + 0x5A827999;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[17] + 0x5A827999;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[18] + 0x5A827999;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[19] + 0x5A827999;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[20] + 0x6ED9EBA1;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[21] + 0x6ED9EBA1;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[22] + 0x6ED9EBA1;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[23] + 0x6ED9EBA1;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[24] + 0x6ED9EBA1;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[25] + 0x6ED9EBA1;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[26] + 0x6ED9EBA1;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[27] + 0x6ED9EBA1;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[28] + 0x6ED9EBA1;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[29] + 0x6ED9EBA1;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[30] + 0x6ED9EBA1;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[31] + 0x6ED9EBA1;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[32] + 0x6ED9EBA1;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[33] + 0x6ED9EBA1;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[34] + 0x6ED9EBA1;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[35] + 0x6ED9EBA1;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[36] + 0x6ED9EBA1;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[37] + 0x6ED9EBA1;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[38] + 0x6ED9EBA1;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[39] + 0x6ED9EBA1;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[40] + 0x8F1BBCDC;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[41] + 0x8F1BBCDC;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[42] + 0x8F1BBCDC;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[43] + 0x8F1BBCDC;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[44] + 0x8F1BBCDC;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[45] + 0x8F1BBCDC;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[46] + 0x8F1BBCDC;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[47] + 0x8F1BBCDC;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[48] + 0x8F1BBCDC;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[49] + 0x8F1BBCDC;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[50] + 0x8F1BBCDC;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[51] + 0x8F1BBCDC;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[52] + 0x8F1BBCDC;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[53] + 0x8F1BBCDC;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[54] + 0x8F1BBCDC;
C = ((C << 30) | (C >>> 2));
E = E + ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[55] + 0x8F1BBCDC;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[56] + 0x8F1BBCDC;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[57] + 0x8F1BBCDC;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[58] + 0x8F1BBCDC;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[59] + 0x8F1BBCDC;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[60] + 0xCA62C1D6;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[61] + 0xCA62C1D6;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[62] + 0xCA62C1D6;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[63] + 0xCA62C1D6;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[64] + 0xCA62C1D6;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[65] + 0xCA62C1D6;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[66] + 0xCA62C1D6;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[67] + 0xCA62C1D6;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[68] + 0xCA62C1D6;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[69] + 0xCA62C1D6;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[70] + 0xCA62C1D6;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[71] + 0xCA62C1D6;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[72] + 0xCA62C1D6;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[73] + 0xCA62C1D6;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[74] + 0xCA62C1D6;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[75] + 0xCA62C1D6;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[76] + 0xCA62C1D6;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[77] + 0xCA62C1D6;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[78] + 0xCA62C1D6;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[79] + 0xCA62C1D6;
C = ((C << 30) | (C >>> 2));
H0 += A;
H1 += B;
H2 += C;
H3 += D;
H4 += E;
// debug(80, H0, H1, H2, H3, H4);
}
private static final String toHexString(byte[] b)
{
final String hexChar = "0123456789ABCDEF";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < b.length; i++)
{
sb.append(hexChar.charAt((b[i] >> 4) & 0x0f));
sb.append(hexChar.charAt(b[i] & 0x0f));
}
return sb.toString();
}
public static void main(String[] args)
{
SHA1 sha = new SHA1();
byte[] dig1 = new byte[20];
byte[] dig2 = new byte[20];
byte[] dig3 = new byte[20];
/*
* We do not specify a charset name for getBytes(), since we assume that
* the JVM's default encoder maps the _used_ ASCII characters exactly as
* getBytes("US-ASCII") would do. (Ah, yes, too lazy to catch the
* exception that can be thrown by getBytes("US-ASCII")). Note: This has
* no effect on the SHA-1 implementation, this is just for the following
* test code.
*/
sha.update("abc".getBytes());
sha.digest(dig1);
sha.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes());
sha.digest(dig2);
for (int i = 0; i < 1000000; i++)
sha.update((byte) 'a');
sha.digest(dig3);
String dig1_res = toHexString(dig1);
String dig2_res = toHexString(dig2);
String dig3_res = toHexString(dig3);
String dig1_ref = "A9993E364706816ABA3E25717850C26C9CD0D89D";
String dig2_ref = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1";
String dig3_ref = "34AA973CD4C4DAA4F61EEB2BDBAD27316534016F";
if (dig1_res.equals(dig1_ref))
System.out.println("SHA-1 Test 1 OK.");
else
System.out.println("SHA-1 Test 1 FAILED.");
if (dig2_res.equals(dig2_ref))
System.out.println("SHA-1 Test 2 OK.");
else
System.out.println("SHA-1 Test 2 FAILED.");
if (dig3_res.equals(dig3_ref))
System.out.println("SHA-1 Test 3 OK.");
else
System.out.println("SHA-1 Test 3 FAILED.");
if (dig3_res.equals(dig3_ref))
System.out.println("SHA-1 Test 3 OK.");
else
System.out.println("SHA-1 Test 3 FAILED.");
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/digest/SHA1.java
|
Java
|
asf20
| 18,717
|
package com.trilead.ssh2.crypto.digest;
/**
* Digest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Digest.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public interface Digest
{
public int getDigestLength();
public void update(byte b);
public void update(byte[] b);
public void update(byte b[], int off, int len);
public void reset();
public void digest(byte[] out);
public void digest(byte[] out, int off);
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/digest/Digest.java
|
Java
|
asf20
| 483
|
package com.trilead.ssh2.crypto;
import java.io.CharArrayWriter;
import java.io.IOException;
/**
* Basic Base64 Support.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Base64.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class Base64
{
static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
public static char[] encode(byte[] content)
{
CharArrayWriter cw = new CharArrayWriter((4 * content.length) / 3);
int idx = 0;
int x = 0;
for (int i = 0; i < content.length; i++)
{
if (idx == 0)
x = (content[i] & 0xff) << 16;
else if (idx == 1)
x = x | ((content[i] & 0xff) << 8);
else
x = x | (content[i] & 0xff);
idx++;
if (idx == 3)
{
cw.write(alphabet[x >> 18]);
cw.write(alphabet[(x >> 12) & 0x3f]);
cw.write(alphabet[(x >> 6) & 0x3f]);
cw.write(alphabet[x & 0x3f]);
idx = 0;
}
}
if (idx == 1)
{
cw.write(alphabet[x >> 18]);
cw.write(alphabet[(x >> 12) & 0x3f]);
cw.write('=');
cw.write('=');
}
if (idx == 2)
{
cw.write(alphabet[x >> 18]);
cw.write(alphabet[(x >> 12) & 0x3f]);
cw.write(alphabet[(x >> 6) & 0x3f]);
cw.write('=');
}
return cw.toCharArray();
}
public static byte[] decode(char[] message) throws IOException
{
byte buff[] = new byte[4];
byte dest[] = new byte[message.length];
int bpos = 0;
int destpos = 0;
for (int i = 0; i < message.length; i++)
{
int c = message[i];
if ((c == '\n') || (c == '\r') || (c == ' ') || (c == '\t'))
continue;
if ((c >= 'A') && (c <= 'Z'))
{
buff[bpos++] = (byte) (c - 'A');
}
else if ((c >= 'a') && (c <= 'z'))
{
buff[bpos++] = (byte) ((c - 'a') + 26);
}
else if ((c >= '0') && (c <= '9'))
{
buff[bpos++] = (byte) ((c - '0') + 52);
}
else if (c == '+')
{
buff[bpos++] = 62;
}
else if (c == '/')
{
buff[bpos++] = 63;
}
else if (c == '=')
{
buff[bpos++] = 64;
}
else
{
throw new IOException("Illegal char in base64 code.");
}
if (bpos == 4)
{
bpos = 0;
if (buff[0] == 64)
break;
if (buff[1] == 64)
throw new IOException("Unexpected '=' in base64 code.");
if (buff[2] == 64)
{
int v = (((buff[0] & 0x3f) << 6) | ((buff[1] & 0x3f)));
dest[destpos++] = (byte) (v >> 4);
break;
}
else if (buff[3] == 64)
{
int v = (((buff[0] & 0x3f) << 12) | ((buff[1] & 0x3f) << 6) | ((buff[2] & 0x3f)));
dest[destpos++] = (byte) (v >> 10);
dest[destpos++] = (byte) (v >> 2);
break;
}
else
{
int v = (((buff[0] & 0x3f) << 18) | ((buff[1] & 0x3f) << 12) | ((buff[2] & 0x3f) << 6) | ((buff[3] & 0x3f)));
dest[destpos++] = (byte) (v >> 16);
dest[destpos++] = (byte) (v >> 8);
dest[destpos++] = (byte) (v);
}
}
}
byte[] res = new byte[destpos];
System.arraycopy(dest, 0, res, 0, destpos);
return res;
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/Base64.java
|
Java
|
asf20
| 3,149
|
package com.trilead.ssh2.crypto;
import java.io.IOException;
import java.math.BigInteger;
/**
* SimpleDERReader.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SimpleDERReader.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SimpleDERReader
{
byte[] buffer;
int pos;
int count;
public SimpleDERReader(byte[] b)
{
resetInput(b);
}
public SimpleDERReader(byte[] b, int off, int len)
{
resetInput(b, off, len);
}
public void resetInput(byte[] b)
{
resetInput(b, 0, b.length);
}
public void resetInput(byte[] b, int off, int len)
{
buffer = b;
pos = off;
count = len;
}
private byte readByte() throws IOException
{
if (count <= 0)
throw new IOException("DER byte array: out of data");
count--;
return buffer[pos++];
}
private byte[] readBytes(int len) throws IOException
{
if (len > count)
throw new IOException("DER byte array: out of data");
byte[] b = new byte[len];
System.arraycopy(buffer, pos, b, 0, len);
pos += len;
count -= len;
return b;
}
public int available()
{
return count;
}
private int readLength() throws IOException
{
int len = readByte() & 0xff;
if ((len & 0x80) == 0)
return len;
int remain = len & 0x7F;
if (remain == 0)
return -1;
len = 0;
while (remain > 0)
{
len = len << 8;
len = len | (readByte() & 0xff);
remain--;
}
return len;
}
public int ignoreNextObject() throws IOException
{
int type = readByte() & 0xff;
int len = readLength();
if ((len < 0) || len > available())
throw new IOException("Illegal len in DER object (" + len + ")");
readBytes(len);
return type;
}
public BigInteger readInt() throws IOException
{
int type = readByte() & 0xff;
if (type != 0x02)
throw new IOException("Expected DER Integer, but found type " + type);
int len = readLength();
if ((len < 0) || len > available())
throw new IOException("Illegal len in DER object (" + len + ")");
byte[] b = readBytes(len);
BigInteger bi = new BigInteger(b);
return bi;
}
public byte[] readSequenceAsByteArray() throws IOException
{
int type = readByte() & 0xff;
if (type != 0x30)
throw new IOException("Expected DER Sequence, but found type " + type);
int len = readLength();
if ((len < 0) || len > available())
throw new IOException("Illegal len in DER object (" + len + ")");
byte[] b = readBytes(len);
return b;
}
public byte[] readOctetString() throws IOException
{
int type = readByte() & 0xff;
if (type != 0x04)
throw new IOException("Expected DER Octetstring, but found type " + type);
int len = readLength();
if ((len < 0) || len > available())
throw new IOException("Illegal len in DER object (" + len + ")");
byte[] b = readBytes(len);
return b;
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/SimpleDERReader.java
|
Java
|
asf20
| 3,005
|
package com.trilead.ssh2.crypto;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.math.BigInteger;
import com.trilead.ssh2.crypto.cipher.AES;
import com.trilead.ssh2.crypto.cipher.BlockCipher;
import com.trilead.ssh2.crypto.cipher.CBCMode;
import com.trilead.ssh2.crypto.cipher.DES;
import com.trilead.ssh2.crypto.cipher.DESede;
import com.trilead.ssh2.crypto.digest.MD5;
import com.trilead.ssh2.signature.DSAPrivateKey;
import com.trilead.ssh2.signature.RSAPrivateKey;
/**
* PEM Support.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PEMDecoder.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class PEMDecoder
{
public static final int PEM_RSA_PRIVATE_KEY = 1;
public static final int PEM_DSA_PRIVATE_KEY = 2;
private static final int hexToInt(char c)
{
if ((c >= 'a') && (c <= 'f'))
{
return (c - 'a') + 10;
}
if ((c >= 'A') && (c <= 'F'))
{
return (c - 'A') + 10;
}
if ((c >= '0') && (c <= '9'))
{
return (c - '0');
}
throw new IllegalArgumentException("Need hex char");
}
private static byte[] hexToByteArray(String hex)
{
if (hex == null)
throw new IllegalArgumentException("null argument");
if ((hex.length() % 2) != 0)
throw new IllegalArgumentException("Uneven string length in hex encoding.");
byte decoded[] = new byte[hex.length() / 2];
for (int i = 0; i < decoded.length; i++)
{
int hi = hexToInt(hex.charAt(i * 2));
int lo = hexToInt(hex.charAt((i * 2) + 1));
decoded[i] = (byte) (hi * 16 + lo);
}
return decoded;
}
private static byte[] generateKeyFromPasswordSaltWithMD5(byte[] password, byte[] salt, int keyLen)
throws IOException
{
if (salt.length < 8)
throw new IllegalArgumentException("Salt needs to be at least 8 bytes for key generation.");
MD5 md5 = new MD5();
byte[] key = new byte[keyLen];
byte[] tmp = new byte[md5.getDigestLength()];
while (true)
{
md5.update(password, 0, password.length);
md5.update(salt, 0, 8); // ARGH we only use the first 8 bytes of the
// salt in this step.
// This took me two hours until I got AES-xxx running.
int copy = (keyLen < tmp.length) ? keyLen : tmp.length;
md5.digest(tmp, 0);
System.arraycopy(tmp, 0, key, key.length - keyLen, copy);
keyLen -= copy;
if (keyLen == 0)
return key;
md5.update(tmp, 0, tmp.length);
}
}
private static byte[] removePadding(byte[] buff, int blockSize) throws IOException
{
/* Removes RFC 1423/PKCS #7 padding */
int rfc_1423_padding = buff[buff.length - 1] & 0xff;
if ((rfc_1423_padding < 1) || (rfc_1423_padding > blockSize))
throw new IOException("Decrypted PEM has wrong padding, did you specify the correct password?");
for (int i = 2; i <= rfc_1423_padding; i++)
{
if (buff[buff.length - i] != rfc_1423_padding)
throw new IOException("Decrypted PEM has wrong padding, did you specify the correct password?");
}
byte[] tmp = new byte[buff.length - rfc_1423_padding];
System.arraycopy(buff, 0, tmp, 0, buff.length - rfc_1423_padding);
return tmp;
}
public static final PEMStructure parsePEM(char[] pem) throws IOException
{
PEMStructure ps = new PEMStructure();
String line = null;
BufferedReader br = new BufferedReader(new CharArrayReader(pem));
String endLine = null;
while (true)
{
line = br.readLine();
if (line == null)
throw new IOException("Invalid PEM structure, '-----BEGIN...' missing");
line = line.trim();
if (line.startsWith("-----BEGIN DSA PRIVATE KEY-----"))
{
endLine = "-----END DSA PRIVATE KEY-----";
ps.pemType = PEM_DSA_PRIVATE_KEY;
break;
}
if (line.startsWith("-----BEGIN RSA PRIVATE KEY-----"))
{
endLine = "-----END RSA PRIVATE KEY-----";
ps.pemType = PEM_RSA_PRIVATE_KEY;
break;
}
}
while (true)
{
line = br.readLine();
if (line == null)
throw new IOException("Invalid PEM structure, " + endLine + " missing");
line = line.trim();
int sem_idx = line.indexOf(':');
if (sem_idx == -1)
break;
String name = line.substring(0, sem_idx + 1);
String value = line.substring(sem_idx + 1);
String values[] = value.split(",");
for (int i = 0; i < values.length; i++)
values[i] = values[i].trim();
// Proc-Type: 4,ENCRYPTED
// DEK-Info: DES-EDE3-CBC,579B6BE3E5C60483
if ("Proc-Type:".equals(name))
{
ps.procType = values;
continue;
}
if ("DEK-Info:".equals(name))
{
ps.dekInfo = values;
continue;
}
/* Ignore line */
}
StringBuffer keyData = new StringBuffer();
while (true)
{
if (line == null)
throw new IOException("Invalid PEM structure, " + endLine + " missing");
line = line.trim();
if (line.startsWith(endLine))
break;
keyData.append(line);
line = br.readLine();
}
char[] pem_chars = new char[keyData.length()];
keyData.getChars(0, pem_chars.length, pem_chars, 0);
ps.data = Base64.decode(pem_chars);
if (ps.data.length == 0)
throw new IOException("Invalid PEM structure, no data available");
return ps;
}
private static final void decryptPEM(PEMStructure ps, byte[] pw) throws IOException
{
if (ps.dekInfo == null)
throw new IOException("Broken PEM, no mode and salt given, but encryption enabled");
if (ps.dekInfo.length != 2)
throw new IOException("Broken PEM, DEK-Info is incomplete!");
String algo = ps.dekInfo[0];
byte[] salt = hexToByteArray(ps.dekInfo[1]);
BlockCipher bc = null;
if (algo.equals("DES-EDE3-CBC"))
{
DESede des3 = new DESede();
des3.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 24));
bc = new CBCMode(des3, salt, false);
}
else if (algo.equals("DES-CBC"))
{
DES des = new DES();
des.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 8));
bc = new CBCMode(des, salt, false);
}
else if (algo.equals("AES-128-CBC"))
{
AES aes = new AES();
aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 16));
bc = new CBCMode(aes, salt, false);
}
else if (algo.equals("AES-192-CBC"))
{
AES aes = new AES();
aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 24));
bc = new CBCMode(aes, salt, false);
}
else if (algo.equals("AES-256-CBC"))
{
AES aes = new AES();
aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 32));
bc = new CBCMode(aes, salt, false);
}
else
{
throw new IOException("Cannot decrypt PEM structure, unknown cipher " + algo);
}
if ((ps.data.length % bc.getBlockSize()) != 0)
throw new IOException("Invalid PEM structure, size of encrypted block is not a multiple of "
+ bc.getBlockSize());
/* Now decrypt the content */
byte[] dz = new byte[ps.data.length];
for (int i = 0; i < ps.data.length / bc.getBlockSize(); i++)
{
bc.transformBlock(ps.data, i * bc.getBlockSize(), dz, i * bc.getBlockSize());
}
/* Now check and remove RFC 1423/PKCS #7 padding */
dz = removePadding(dz, bc.getBlockSize());
ps.data = dz;
ps.dekInfo = null;
ps.procType = null;
}
public static final boolean isPEMEncrypted(PEMStructure ps) throws IOException
{
if (ps.procType == null)
return false;
if (ps.procType.length != 2)
throw new IOException("Unknown Proc-Type field.");
if ("4".equals(ps.procType[0]) == false)
throw new IOException("Unknown Proc-Type field (" + ps.procType[0] + ")");
if ("ENCRYPTED".equals(ps.procType[1]))
return true;
return false;
}
public static Object decode(char[] pem, String password) throws IOException
{
PEMStructure ps = parsePEM(pem);
if (isPEMEncrypted(ps))
{
if (password == null)
throw new IOException("PEM is encrypted, but no password was specified");
decryptPEM(ps, password.getBytes("ISO-8859-1"));
}
if (ps.pemType == PEM_DSA_PRIVATE_KEY)
{
SimpleDERReader dr = new SimpleDERReader(ps.data);
byte[] seq = dr.readSequenceAsByteArray();
if (dr.available() != 0)
throw new IOException("Padding in DSA PRIVATE KEY DER stream.");
dr.resetInput(seq);
BigInteger version = dr.readInt();
if (version.compareTo(BigInteger.ZERO) != 0)
throw new IOException("Wrong version (" + version + ") in DSA PRIVATE KEY DER stream.");
BigInteger p = dr.readInt();
BigInteger q = dr.readInt();
BigInteger g = dr.readInt();
BigInteger y = dr.readInt();
BigInteger x = dr.readInt();
if (dr.available() != 0)
throw new IOException("Padding in DSA PRIVATE KEY DER stream.");
return new DSAPrivateKey(p, q, g, y, x);
}
if (ps.pemType == PEM_RSA_PRIVATE_KEY)
{
SimpleDERReader dr = new SimpleDERReader(ps.data);
byte[] seq = dr.readSequenceAsByteArray();
if (dr.available() != 0)
throw new IOException("Padding in RSA PRIVATE KEY DER stream.");
dr.resetInput(seq);
BigInteger version = dr.readInt();
if ((version.compareTo(BigInteger.ZERO) != 0) && (version.compareTo(BigInteger.ONE) != 0))
throw new IOException("Wrong version (" + version + ") in RSA PRIVATE KEY DER stream.");
BigInteger n = dr.readInt();
BigInteger e = dr.readInt();
BigInteger d = dr.readInt();
return new RSAPrivateKey(d, e, n);
}
throw new IOException("PEM problem: it is of unknown type");
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/PEMDecoder.java
|
Java
|
asf20
| 9,657
|
package com.trilead.ssh2.crypto;
import com.trilead.ssh2.compression.CompressionFactory;
import com.trilead.ssh2.crypto.cipher.BlockCipherFactory;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.transport.KexManager;
/**
* CryptoWishList.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: CryptoWishList.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class CryptoWishList
{
public String[] kexAlgorithms = KexManager.getDefaultKexAlgorithmList();
public String[] serverHostKeyAlgorithms = KexManager.getDefaultServerHostkeyAlgorithmList();
public String[] c2s_enc_algos = BlockCipherFactory.getDefaultCipherList();
public String[] s2c_enc_algos = BlockCipherFactory.getDefaultCipherList();
public String[] c2s_mac_algos = MAC.getMacList();
public String[] s2c_mac_algos = MAC.getMacList();
public String[] c2s_comp_algos = CompressionFactory.getDefaultCompressorList();
public String[] s2c_comp_algos = CompressionFactory.getDefaultCompressorList();
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/CryptoWishList.java
|
Java
|
asf20
| 1,043
|
package com.trilead.ssh2.crypto.dh;
import java.math.BigInteger;
import java.security.SecureRandom;
import com.trilead.ssh2.DHGexParameters;
import com.trilead.ssh2.crypto.digest.HashForSSH2Types;
/**
* DhGroupExchange.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DhGroupExchange.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class DhGroupExchange
{
/* Given by the standard */
private BigInteger p;
private BigInteger g;
/* Client public and private */
private BigInteger e;
private BigInteger x;
/* Server public */
private BigInteger f;
/* Shared secret */
private BigInteger k;
public DhGroupExchange(BigInteger p, BigInteger g)
{
this.p = p;
this.g = g;
}
public void init(SecureRandom rnd)
{
k = null;
x = new BigInteger(p.bitLength() - 1, rnd);
e = g.modPow(x, p);
}
/**
* @return Returns the e.
*/
public BigInteger getE()
{
if (e == null)
throw new IllegalStateException("Not initialized!");
return e;
}
/**
* @return Returns the shared secret k.
*/
public BigInteger getK()
{
if (k == null)
throw new IllegalStateException("Shared secret not yet known, need f first!");
return k;
}
/**
* Sets f and calculates the shared secret.
*/
public void setF(BigInteger f)
{
if (e == null)
throw new IllegalStateException("Not initialized!");
BigInteger zero = BigInteger.valueOf(0);
if (zero.compareTo(f) >= 0 || p.compareTo(f) <= 0)
throw new IllegalArgumentException("Invalid f specified!");
this.f = f;
this.k = f.modPow(x, p);
}
public byte[] calculateH(byte[] clientversion, byte[] serverversion, byte[] clientKexPayload,
byte[] serverKexPayload, byte[] hostKey, DHGexParameters para)
{
HashForSSH2Types hash = new HashForSSH2Types("SHA1");
hash.updateByteString(clientversion);
hash.updateByteString(serverversion);
hash.updateByteString(clientKexPayload);
hash.updateByteString(serverKexPayload);
hash.updateByteString(hostKey);
if (para.getMin_group_len() > 0)
hash.updateUINT32(para.getMin_group_len());
hash.updateUINT32(para.getPref_group_len());
if (para.getMax_group_len() > 0)
hash.updateUINT32(para.getMax_group_len());
hash.updateBigInt(p);
hash.updateBigInt(g);
hash.updateBigInt(e);
hash.updateBigInt(f);
hash.updateBigInt(k);
return hash.getDigest();
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/dh/DhGroupExchange.java
|
Java
|
asf20
| 2,477
|
package com.trilead.ssh2.crypto.dh;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.SecureRandom;
import com.trilead.ssh2.crypto.digest.HashForSSH2Types;
import com.trilead.ssh2.log.Logger;
/**
* DhExchange.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DhExchange.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class DhExchange
{
private static final Logger log = Logger.getLogger(DhExchange.class);
/* Given by the standard */
static final BigInteger p1, p14;
static final BigInteger g;
BigInteger p;
/* Client public and private */
BigInteger e;
BigInteger x;
/* Server public */
BigInteger f;
/* Shared secret */
BigInteger k;
static
{
final String p1_string = "17976931348623159077083915679378745319786029604875"
+ "60117064444236841971802161585193689478337958649255415021805654859805036464"
+ "40548199239100050792877003355816639229553136239076508735759914822574862575"
+ "00742530207744771258955095793777842444242661733472762929938766870920560605"
+ "0270810842907692932019128194467627007";
final String p14_string = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129"
+ "024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0"
+ "A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB"
+ "6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A"
+ "163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208"
+ "552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36C"
+ "E3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF69558171"
+ "83995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF";
p1 = new BigInteger(p1_string);
p14 = new BigInteger(p14_string, 16);
g = new BigInteger("2");
}
public DhExchange()
{
}
public void init(int group, SecureRandom rnd)
{
k = null;
if (group == 1)
p = p1;
else if (group == 14)
p = p14;
else
throw new IllegalArgumentException("Unknown DH group " + group);
x = new BigInteger(p.bitLength() - 1, rnd);
e = g.modPow(x, p);
}
/**
* @return Returns the e.
* @throws IllegalStateException
*/
public BigInteger getE()
{
if (e == null)
throw new IllegalStateException("DhDsaExchange not initialized!");
return e;
}
/**
* @return Returns the shared secret k.
* @throws IllegalStateException
*/
public BigInteger getK()
{
if (k == null)
throw new IllegalStateException("Shared secret not yet known, need f first!");
return k;
}
/**
* @param f
*/
public void setF(BigInteger f)
{
if (e == null)
throw new IllegalStateException("DhDsaExchange not initialized!");
BigInteger zero = BigInteger.valueOf(0);
if (zero.compareTo(f) >= 0 || p.compareTo(f) <= 0)
throw new IllegalArgumentException("Invalid f specified!");
this.f = f;
this.k = f.modPow(x, p);
}
public byte[] calculateH(byte[] clientversion, byte[] serverversion, byte[] clientKexPayload,
byte[] serverKexPayload, byte[] hostKey) throws UnsupportedEncodingException
{
HashForSSH2Types hash = new HashForSSH2Types("SHA1");
if (log.isEnabled())
{
log.log(90, "Client: '" + new String(clientversion, "ISO-8859-1") + "'");
log.log(90, "Server: '" + new String(serverversion, "ISO-8859-1") + "'");
}
hash.updateByteString(clientversion);
hash.updateByteString(serverversion);
hash.updateByteString(clientKexPayload);
hash.updateByteString(serverKexPayload);
hash.updateByteString(hostKey);
hash.updateBigInt(e);
hash.updateBigInt(f);
hash.updateBigInt(k);
return hash.getDigest();
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/dh/DhExchange.java
|
Java
|
asf20
| 3,808
|
package com.trilead.ssh2.crypto;
/**
* Parsed PEM structure.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PEMStructure.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class PEMStructure
{
public int pemType;
String dekInfo[];
String procType[];
public byte[] data;
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/PEMStructure.java
|
Java
|
asf20
| 327
|
package com.trilead.ssh2.crypto;
import java.math.BigInteger;
import com.trilead.ssh2.crypto.digest.HashForSSH2Types;
/**
* Establishes key material for iv/key/mac (both directions).
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KeyMaterial.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class KeyMaterial
{
public byte[] initial_iv_client_to_server;
public byte[] initial_iv_server_to_client;
public byte[] enc_key_client_to_server;
public byte[] enc_key_server_to_client;
public byte[] integrity_key_client_to_server;
public byte[] integrity_key_server_to_client;
private static byte[] calculateKey(HashForSSH2Types sh, BigInteger K, byte[] H, byte type, byte[] SessionID,
int keyLength)
{
byte[] res = new byte[keyLength];
int dglen = sh.getDigestLength();
int numRounds = (keyLength + dglen - 1) / dglen;
byte[][] tmp = new byte[numRounds][];
sh.reset();
sh.updateBigInt(K);
sh.updateBytes(H);
sh.updateByte(type);
sh.updateBytes(SessionID);
tmp[0] = sh.getDigest();
int off = 0;
int produced = Math.min(dglen, keyLength);
System.arraycopy(tmp[0], 0, res, off, produced);
keyLength -= produced;
off += produced;
for (int i = 1; i < numRounds; i++)
{
sh.updateBigInt(K);
sh.updateBytes(H);
for (int j = 0; j < i; j++)
sh.updateBytes(tmp[j]);
tmp[i] = sh.getDigest();
produced = Math.min(dglen, keyLength);
System.arraycopy(tmp[i], 0, res, off, produced);
keyLength -= produced;
off += produced;
}
return res;
}
public static KeyMaterial create(String hashType, byte[] H, BigInteger K, byte[] SessionID, int keyLengthCS,
int blockSizeCS, int macLengthCS, int keyLengthSC, int blockSizeSC, int macLengthSC)
throws IllegalArgumentException
{
KeyMaterial km = new KeyMaterial();
HashForSSH2Types sh = new HashForSSH2Types(hashType);
km.initial_iv_client_to_server = calculateKey(sh, K, H, (byte) 'A', SessionID, blockSizeCS);
km.initial_iv_server_to_client = calculateKey(sh, K, H, (byte) 'B', SessionID, blockSizeSC);
km.enc_key_client_to_server = calculateKey(sh, K, H, (byte) 'C', SessionID, keyLengthCS);
km.enc_key_server_to_client = calculateKey(sh, K, H, (byte) 'D', SessionID, keyLengthSC);
km.integrity_key_client_to_server = calculateKey(sh, K, H, (byte) 'E', SessionID, macLengthCS);
km.integrity_key_server_to_client = calculateKey(sh, K, H, (byte) 'F', SessionID, macLengthSC);
return km;
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/crypto/KeyMaterial.java
|
Java
|
asf20
| 2,566
|
package com.trilead.ssh2;
/**
* A <code>SFTPv3DirectoryEntry</code> as returned by {@link SFTPv3Client#ls(String)}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3DirectoryEntry.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SFTPv3DirectoryEntry
{
/**
* A relative name within the directory, without any path components.
*/
public String filename;
/**
* An expanded format for the file name, similar to what is returned by
* "ls -l" on Un*x systems.
* <p>
* The format of this field is unspecified by the SFTP v3 protocol.
* It MUST be suitable for use in the output of a directory listing
* command (in fact, the recommended operation for a directory listing
* command is to simply display this data). However, clients SHOULD NOT
* attempt to parse the longname field for file attributes; they SHOULD
* use the attrs field instead.
* <p>
* The recommended format for the longname field is as follows:<br>
* <code>-rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer</code>
*/
public String longEntry;
/**
* The attributes of this entry.
*/
public SFTPv3FileAttributes attributes;
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/SFTPv3DirectoryEntry.java
|
Java
|
asf20
| 1,230
|
package com.trilead.ssh2.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collections;
import java.util.LinkedList;
import com.trilead.ssh2.log.Logger;
/**
* TimeoutService (beta). Here you can register a timeout.
* <p>
* Implemented having large scale programs in mind: if you open many concurrent SSH connections
* that rely on timeouts, then there will be only one timeout thread. Once all timeouts
* have expired/are cancelled, the thread will (sooner or later) exit.
* Only after new timeouts arrive a new thread (singleton) will be instantiated.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TimeoutService.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class TimeoutService
{
private static final Logger log = Logger.getLogger(TimeoutService.class);
public static class TimeoutToken implements Comparable
{
private long runTime;
private Runnable handler;
private TimeoutToken(long runTime, Runnable handler)
{
this.runTime = runTime;
this.handler = handler;
}
public int compareTo(Object o)
{
TimeoutToken t = (TimeoutToken) o;
if (runTime > t.runTime)
return 1;
if (runTime == t.runTime)
return 0;
return -1;
}
}
private static class TimeoutThread extends Thread
{
public void run()
{
synchronized (todolist)
{
while (true)
{
if (todolist.size() == 0)
{
timeoutThread = null;
return;
}
long now = System.currentTimeMillis();
TimeoutToken tt = (TimeoutToken) todolist.getFirst();
if (tt.runTime > now)
{
/* Not ready yet, sleep a little bit */
try
{
todolist.wait(tt.runTime - now);
}
catch (InterruptedException e)
{
}
/* We cannot simply go on, since it could be that the token
* was removed (cancelled) or another one has been inserted in
* the meantime.
*/
continue;
}
todolist.removeFirst();
try
{
tt.handler.run();
}
catch (Exception e)
{
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.log(20, "Exeception in Timeout handler:" + e.getMessage() + "(" + sw.toString() + ")");
}
}
}
}
}
/* The list object is also used for locking purposes */
private static final LinkedList todolist = new LinkedList();
private static Thread timeoutThread = null;
/**
* It is assumed that the passed handler will not execute for a long time.
*
* @param runTime
* @param handler
* @return a TimeoutToken that can be used to cancel the timeout.
*/
public static final TimeoutToken addTimeoutHandler(long runTime, Runnable handler)
{
TimeoutToken token = new TimeoutToken(runTime, handler);
synchronized (todolist)
{
todolist.add(token);
Collections.sort(todolist);
if (timeoutThread != null)
timeoutThread.interrupt();
else
{
timeoutThread = new TimeoutThread();
timeoutThread.setDaemon(true);
timeoutThread.start();
}
}
return token;
}
public static final void cancelTimeoutHandler(TimeoutToken token)
{
synchronized (todolist)
{
todolist.remove(token);
if (timeoutThread != null)
timeoutThread.interrupt();
}
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/util/TimeoutService.java
|
Java
|
asf20
| 3,443
|
package com.trilead.ssh2.util;
/**
* Tokenizer. Why? Because StringTokenizer is not available in J2ME.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Tokenizer.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class Tokenizer
{
/**
* Exists because StringTokenizer is not available in J2ME.
* Returns an array with at least 1 entry.
*
* @param source must be non-null
* @param delimiter
* @return an array of Strings
*/
public static String[] parseTokens(String source, char delimiter)
{
int numtoken = 1;
for (int i = 0; i < source.length(); i++)
{
if (source.charAt(i) == delimiter)
numtoken++;
}
String list[] = new String[numtoken];
int nextfield = 0;
for (int i = 0; i < numtoken; i++)
{
if (nextfield >= source.length())
{
list[i] = "";
}
else
{
int idx = source.indexOf(delimiter, nextfield);
if (idx == -1)
idx = source.length();
list[i] = source.substring(nextfield, idx);
nextfield = idx + 1;
}
}
return list;
}
}
|
0359xiaodong-sydy
|
src/com/trilead/ssh2/util/Tokenizer.java
|
Java
|
asf20
| 1,104
|
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class InfBlocks{
static final private int MANY=1440;
// And'ing with mask[n] masks the lower n bits
static final private int[] inflate_mask = {
0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff,
0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff,
0x00007fff, 0x0000ffff
};
// Table for deflate from PKZIP's appnote.txt.
static final int[] border = { // Order of the bit length code lengths
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
};
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
static final private int TYPE=0; // get type bits (3, including end bit)
static final private int LENS=1; // get lengths for stored
static final private int STORED=2;// processing stored block
static final private int TABLE=3; // get table lengths
static final private int BTREE=4; // get bit lengths tree for a dynamic block
static final private int DTREE=5; // get length, distance trees for a dynamic block
static final private int CODES=6; // processing fixed or dynamic block
static final private int DRY=7; // output remaining window bytes
static final private int DONE=8; // finished last block, done
static final private int BAD=9; // ot a data error--stuck here
int mode; // current inflate_block mode
int left; // if STORED, bytes left to copy
int table; // table lengths (14 bits)
int index; // index into blens (or border)
int[] blens; // bit lengths of codes
int[] bb=new int[1]; // bit length tree depth
int[] tb=new int[1]; // bit length decoding tree
InfCodes codes=new InfCodes(); // if CODES, current state
int last; // true if this block is the last block
// mode independent information
int bitk; // bits in bit buffer
int bitb; // bit buffer
int[] hufts; // single malloc for tree space
byte[] window; // sliding window
int end; // one byte after sliding window
int read; // window read pointer
int write; // window write pointer
Object checkfn; // check function
long check; // check on output
InfTree inftree=new InfTree();
InfBlocks(ZStream z, Object checkfn, int w){
hufts=new int[MANY*3];
window=new byte[w];
end=w;
this.checkfn = checkfn;
mode = TYPE;
reset(z, null);
}
void reset(ZStream z, long[] c){
if(c!=null) c[0]=check;
if(mode==BTREE || mode==DTREE){
}
if(mode==CODES){
codes.free(z);
}
mode=TYPE;
bitk=0;
bitb=0;
read=write=0;
if(checkfn != null)
z.adler=check=z._adler.adler32(0L, null, 0, 0);
}
int proc(ZStream z, int r){
int t; // temporary storage
int b; // bit buffer
int k; // bits in bit buffer
int p; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
// copy input/output information to locals (UPDATE macro restores)
{p=z.next_in_index;n=z.avail_in;b=bitb;k=bitk;}
{q=write;m=(int)(q<read?read-q-1:end-q);}
// process input based on current state
while(true){
switch (mode){
case TYPE:
while(k<(3)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
t = (int)(b & 7);
last = t & 1;
switch (t >>> 1){
case 0: // stored
{b>>>=(3);k-=(3);}
t = k & 7; // go to byte boundary
{b>>>=(t);k-=(t);}
mode = LENS; // get length of stored block
break;
case 1: // fixed
{
int[] bl=new int[1];
int[] bd=new int[1];
int[][] tl=new int[1][];
int[][] td=new int[1][];
InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
codes.init(bl[0], bd[0], tl[0], 0, td[0], 0, z);
}
{b>>>=(3);k-=(3);}
mode = CODES;
break;
case 2: // dynamic
{b>>>=(3);k-=(3);}
mode = TABLE;
break;
case 3: // illegal
{b>>>=(3);k-=(3);}
mode = BAD;
z.msg = "invalid block type";
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
}
break;
case LENS:
while(k<(32)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
if ((((~b) >>> 16) & 0xffff) != (b & 0xffff)){
mode = BAD;
z.msg = "invalid stored block lengths";
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
}
left = (b & 0xffff);
b = k = 0; // dump bits
mode = left!=0 ? STORED : (last!=0 ? DRY : TYPE);
break;
case STORED:
if (n == 0){
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
}
if(m==0){
if(q==end&&read!=0){
q=0; m=(int)(q<read?read-q-1:end-q);
}
if(m==0){
write=q;
r=inflate_flush(z,r);
q=write;m=(int)(q<read?read-q-1:end-q);
if(q==end&&read!=0){
q=0; m=(int)(q<read?read-q-1:end-q);
}
if(m==0){
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
}
}
}
r=Z_OK;
t = left;
if(t>n) t = n;
if(t>m) t = m;
System.arraycopy(z.next_in, p, window, q, t);
p += t; n -= t;
q += t; m -= t;
if ((left -= t) != 0)
break;
mode = last!=0 ? DRY : TYPE;
break;
case TABLE:
while(k<(14)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
table = t = (b & 0x3fff);
if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
{
mode = BAD;
z.msg = "too many length or distance symbols";
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
}
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
if(blens==null || blens.length<t){
blens=new int[t];
}
else{
for(int i=0; i<t; i++){blens[i]=0;}
}
{b>>>=(14);k-=(14);}
index = 0;
mode = BTREE;
case BTREE:
while (index < 4 + (table >>> 10)){
while(k<(3)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
blens[border[index++]] = b&7;
{b>>>=(3);k-=(3);}
}
while(index < 19){
blens[border[index++]] = 0;
}
bb[0] = 7;
t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z);
if (t != Z_OK){
r = t;
if (r == Z_DATA_ERROR){
blens=null;
mode = BAD;
}
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
}
index = 0;
mode = DTREE;
case DTREE:
while (true){
t = table;
if(!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))){
break;
}
int[] h;
int i, j, c;
t = bb[0];
while(k<(t)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
if(tb[0]==-1){
//System.err.println("null...");
}
t=hufts[(tb[0]+(b&inflate_mask[t]))*3+1];
c=hufts[(tb[0]+(b&inflate_mask[t]))*3+2];
if (c < 16){
b>>>=(t);k-=(t);
blens[index++] = c;
}
else { // c == 16..18
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
while(k<(t+i)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
b>>>=(t);k-=(t);
j += (b & inflate_mask[i]);
b>>>=(i);k-=(i);
i = index;
t = table;
if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
(c == 16 && i < 1)){
blens=null;
mode = BAD;
z.msg = "invalid bit length repeat";
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
}
c = c == 16 ? blens[i-1] : 0;
do{
blens[i++] = c;
}
while (--j!=0);
index = i;
}
}
tb[0]=-1;
{
int[] bl=new int[1];
int[] bd=new int[1];
int[] tl=new int[1];
int[] td=new int[1];
bl[0] = 9; // must be <= 9 for lookahead assumptions
bd[0] = 6; // must be <= 9 for lookahead assumptions
t = table;
t = inftree.inflate_trees_dynamic(257 + (t & 0x1f),
1 + ((t >> 5) & 0x1f),
blens, bl, bd, tl, td, hufts, z);
if (t != Z_OK){
if (t == Z_DATA_ERROR){
blens=null;
mode = BAD;
}
r = t;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z,r);
}
codes.init(bl[0], bd[0], hufts, tl[0], hufts, td[0], z);
}
mode = CODES;
case CODES:
bitb=b; bitk=k;
z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
if ((r = codes.proc(this, z, r)) != Z_STREAM_END){
return inflate_flush(z, r);
}
r = Z_OK;
codes.free(z);
p=z.next_in_index; n=z.avail_in;b=bitb;k=bitk;
q=write;m=(int)(q<read?read-q-1:end-q);
if (last==0){
mode = TYPE;
break;
}
mode = DRY;
case DRY:
write=q;
r=inflate_flush(z, r);
q=write; m=(int)(q<read?read-q-1:end-q);
if (read != write){
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z, r);
}
mode = DONE;
case DONE:
r = Z_STREAM_END;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z, r);
case BAD:
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z, r);
default:
r = Z_STREAM_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(z, r);
}
}
}
void free(ZStream z){
reset(z, null);
window=null;
hufts=null;
//ZFREE(z, s);
}
void set_dictionary(byte[] d, int start, int n){
System.arraycopy(d, start, window, 0, n);
read = write = n;
}
// Returns true if inflate is currently at the end of a block generated
// by Z_SYNC_FLUSH or Z_FULL_FLUSH.
int sync_point(){
return mode == LENS ? 1 : 0;
}
// copy as much as possible from the sliding window to the output area
int inflate_flush(ZStream z, int r){
int n;
int p;
int q;
// local copies of source and destination pointers
p = z.next_out_index;
q = read;
// compute number of bytes to copy as far as end of window
n = (int)((q <= write ? write : end) - q);
if (n > z.avail_out) n = z.avail_out;
if (n!=0 && r == Z_BUF_ERROR) r = Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if(checkfn != null)
z.adler=check=z._adler.adler32(check, window, q, n);
// copy as far as end of window
System.arraycopy(window, q, z.next_out, p, n);
p += n;
q += n;
// see if more to copy at beginning of window
if (q == end){
// wrap pointers
q = 0;
if (write == end)
write = 0;
// compute bytes to copy
n = write - q;
if (n > z.avail_out) n = z.avail_out;
if (n!=0 && r == Z_BUF_ERROR) r = Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if(checkfn != null)
z.adler=check=z._adler.adler32(check, window, q, n);
// copy
System.arraycopy(window, q, z.next_out, p, n);
p += n;
q += n;
}
// update pointers
z.next_out_index = p;
read = q;
// done
return r;
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/InfBlocks.java
|
Java
|
asf20
| 15,158
|
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class StaticTree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
static final short[] static_ltree = {
12, 8, 140, 8, 76, 8, 204, 8, 44, 8,
172, 8, 108, 8, 236, 8, 28, 8, 156, 8,
92, 8, 220, 8, 60, 8, 188, 8, 124, 8,
252, 8, 2, 8, 130, 8, 66, 8, 194, 8,
34, 8, 162, 8, 98, 8, 226, 8, 18, 8,
146, 8, 82, 8, 210, 8, 50, 8, 178, 8,
114, 8, 242, 8, 10, 8, 138, 8, 74, 8,
202, 8, 42, 8, 170, 8, 106, 8, 234, 8,
26, 8, 154, 8, 90, 8, 218, 8, 58, 8,
186, 8, 122, 8, 250, 8, 6, 8, 134, 8,
70, 8, 198, 8, 38, 8, 166, 8, 102, 8,
230, 8, 22, 8, 150, 8, 86, 8, 214, 8,
54, 8, 182, 8, 118, 8, 246, 8, 14, 8,
142, 8, 78, 8, 206, 8, 46, 8, 174, 8,
110, 8, 238, 8, 30, 8, 158, 8, 94, 8,
222, 8, 62, 8, 190, 8, 126, 8, 254, 8,
1, 8, 129, 8, 65, 8, 193, 8, 33, 8,
161, 8, 97, 8, 225, 8, 17, 8, 145, 8,
81, 8, 209, 8, 49, 8, 177, 8, 113, 8,
241, 8, 9, 8, 137, 8, 73, 8, 201, 8,
41, 8, 169, 8, 105, 8, 233, 8, 25, 8,
153, 8, 89, 8, 217, 8, 57, 8, 185, 8,
121, 8, 249, 8, 5, 8, 133, 8, 69, 8,
197, 8, 37, 8, 165, 8, 101, 8, 229, 8,
21, 8, 149, 8, 85, 8, 213, 8, 53, 8,
181, 8, 117, 8, 245, 8, 13, 8, 141, 8,
77, 8, 205, 8, 45, 8, 173, 8, 109, 8,
237, 8, 29, 8, 157, 8, 93, 8, 221, 8,
61, 8, 189, 8, 125, 8, 253, 8, 19, 9,
275, 9, 147, 9, 403, 9, 83, 9, 339, 9,
211, 9, 467, 9, 51, 9, 307, 9, 179, 9,
435, 9, 115, 9, 371, 9, 243, 9, 499, 9,
11, 9, 267, 9, 139, 9, 395, 9, 75, 9,
331, 9, 203, 9, 459, 9, 43, 9, 299, 9,
171, 9, 427, 9, 107, 9, 363, 9, 235, 9,
491, 9, 27, 9, 283, 9, 155, 9, 411, 9,
91, 9, 347, 9, 219, 9, 475, 9, 59, 9,
315, 9, 187, 9, 443, 9, 123, 9, 379, 9,
251, 9, 507, 9, 7, 9, 263, 9, 135, 9,
391, 9, 71, 9, 327, 9, 199, 9, 455, 9,
39, 9, 295, 9, 167, 9, 423, 9, 103, 9,
359, 9, 231, 9, 487, 9, 23, 9, 279, 9,
151, 9, 407, 9, 87, 9, 343, 9, 215, 9,
471, 9, 55, 9, 311, 9, 183, 9, 439, 9,
119, 9, 375, 9, 247, 9, 503, 9, 15, 9,
271, 9, 143, 9, 399, 9, 79, 9, 335, 9,
207, 9, 463, 9, 47, 9, 303, 9, 175, 9,
431, 9, 111, 9, 367, 9, 239, 9, 495, 9,
31, 9, 287, 9, 159, 9, 415, 9, 95, 9,
351, 9, 223, 9, 479, 9, 63, 9, 319, 9,
191, 9, 447, 9, 127, 9, 383, 9, 255, 9,
511, 9, 0, 7, 64, 7, 32, 7, 96, 7,
16, 7, 80, 7, 48, 7, 112, 7, 8, 7,
72, 7, 40, 7, 104, 7, 24, 7, 88, 7,
56, 7, 120, 7, 4, 7, 68, 7, 36, 7,
100, 7, 20, 7, 84, 7, 52, 7, 116, 7,
3, 8, 131, 8, 67, 8, 195, 8, 35, 8,
163, 8, 99, 8, 227, 8
};
static final short[] static_dtree = {
0, 5, 16, 5, 8, 5, 24, 5, 4, 5,
20, 5, 12, 5, 28, 5, 2, 5, 18, 5,
10, 5, 26, 5, 6, 5, 22, 5, 14, 5,
30, 5, 1, 5, 17, 5, 9, 5, 25, 5,
5, 5, 21, 5, 13, 5, 29, 5, 3, 5,
19, 5, 11, 5, 27, 5, 7, 5, 23, 5
};
static StaticTree static_l_desc =
new StaticTree(static_ltree, Tree.extra_lbits,
LITERALS+1, L_CODES, MAX_BITS);
static StaticTree static_d_desc =
new StaticTree(static_dtree, Tree.extra_dbits,
0, D_CODES, MAX_BITS);
static StaticTree static_bl_desc =
new StaticTree(null, Tree.extra_blbits,
0, BL_CODES, MAX_BL_BITS);
short[] static_tree; // static tree or null
int[] extra_bits; // extra bits for each code or null
int extra_base; // base index for extra_bits
int elems; // max number of elements in the tree
int max_length; // max bit length for the codes
StaticTree(short[] static_tree,
int[] extra_bits,
int extra_base,
int elems,
int max_length
){
this.static_tree=static_tree;
this.extra_bits=extra_bits;
this.extra_base=extra_base;
this.elems=elems;
this.max_length=max_length;
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/StaticTree.java
|
Java
|
asf20
| 6,164
|
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final public class JZlib{
private static final String version="1.0.2";
public static String version(){return version;}
// compression levels
static final public int Z_NO_COMPRESSION=0;
static final public int Z_BEST_SPEED=1;
static final public int Z_BEST_COMPRESSION=9;
static final public int Z_DEFAULT_COMPRESSION=(-1);
// compression strategy
static final public int Z_FILTERED=1;
static final public int Z_HUFFMAN_ONLY=2;
static final public int Z_DEFAULT_STRATEGY=0;
static final public int Z_NO_FLUSH=0;
static final public int Z_PARTIAL_FLUSH=1;
static final public int Z_SYNC_FLUSH=2;
static final public int Z_FULL_FLUSH=3;
static final public int Z_FINISH=4;
static final public int Z_OK=0;
static final public int Z_STREAM_END=1;
static final public int Z_NEED_DICT=2;
static final public int Z_ERRNO=-1;
static final public int Z_STREAM_ERROR=-2;
static final public int Z_DATA_ERROR=-3;
static final public int Z_MEM_ERROR=-4;
static final public int Z_BUF_ERROR=-5;
static final public int Z_VERSION_ERROR=-6;
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/JZlib.java
|
Java
|
asf20
| 2,803
|
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class Tree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
static final private int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
// end of block literal code
static final int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138=18;
// extra bits for each length code
static final int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
static final int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
static final int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
static final byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
static final int Buf_size=8*2;
// see definition of array dist_code below
static final int DIST_CODE_LEN=512;
static final byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
static final byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
static final int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
static final int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]);
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2];
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over heap elements
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
static void gen_codes(short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count // number of codes at each bit length
){
short[] next_code=new short[MAX_BITS+1]; // next code value for each bit length
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
static int bi_reverse(int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>>=1;
res<<=1;
}
while(--len>0);
return res>>>1;
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/Tree.java
|
Java
|
asf20
| 14,868
|
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
public class ZStreamException extends java.io.IOException {
public ZStreamException() {
super();
}
public ZStreamException(String s) {
super(s);
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/ZStreamException.java
|
Java
|
asf20
| 1,931
|
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
public
final class Deflate{
static final private int MAX_MEM_LEVEL=9;
static final private int Z_DEFAULT_COMPRESSION=-1;
static final private int MAX_WBITS=15; // 32K LZ77 window
static final private int DEF_MEM_LEVEL=8;
static class Config{
int good_length; // reduce lazy search above this match length
int max_lazy; // do not perform lazy search above this match length
int nice_length; // quit search above this match length
int max_chain;
int func;
Config(int good_length, int max_lazy,
int nice_length, int max_chain, int func){
this.good_length=good_length;
this.max_lazy=max_lazy;
this.nice_length=nice_length;
this.max_chain=max_chain;
this.func=func;
}
}
static final private int STORED=0;
static final private int FAST=1;
static final private int SLOW=2;
static final private Config[] config_table;
static{
config_table=new Config[10];
// good lazy nice chain
config_table[0]=new Config(0, 0, 0, 0, STORED);
config_table[1]=new Config(4, 4, 8, 4, FAST);
config_table[2]=new Config(4, 5, 16, 8, FAST);
config_table[3]=new Config(4, 6, 32, 32, FAST);
config_table[4]=new Config(4, 4, 16, 16, SLOW);
config_table[5]=new Config(8, 16, 32, 32, SLOW);
config_table[6]=new Config(8, 16, 128, 128, SLOW);
config_table[7]=new Config(8, 32, 128, 256, SLOW);
config_table[8]=new Config(32, 128, 258, 1024, SLOW);
config_table[9]=new Config(32, 258, 258, 4096, SLOW);
}
static final private String[] z_errmsg = {
"need dictionary", // Z_NEED_DICT 2
"stream end", // Z_STREAM_END 1
"", // Z_OK 0
"file error", // Z_ERRNO (-1)
"stream error", // Z_STREAM_ERROR (-2)
"data error", // Z_DATA_ERROR (-3)
"insufficient memory", // Z_MEM_ERROR (-4)
"buffer error", // Z_BUF_ERROR (-5)
"incompatible version",// Z_VERSION_ERROR (-6)
""
};
// block not completed, need more input or more output
static final private int NeedMore=0;
// block flush performed
static final private int BlockDone=1;
// finish started, need only more output at next deflate
static final private int FinishStarted=2;
// finish done, accept no more input or output
static final private int FinishDone=3;
// preset dictionary flag in zlib header
static final private int PRESET_DICT=0x20;
static final private int Z_FILTERED=1;
static final private int Z_HUFFMAN_ONLY=2;
static final private int Z_DEFAULT_STRATEGY=0;
static final private int Z_NO_FLUSH=0;
static final private int Z_PARTIAL_FLUSH=1;
static final private int Z_SYNC_FLUSH=2;
static final private int Z_FULL_FLUSH=3;
static final private int Z_FINISH=4;
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
static final private int INIT_STATE=42;
static final private int BUSY_STATE=113;
static final private int FINISH_STATE=666;
// The deflate compression method
static final private int Z_DEFLATED=8;
static final private int STORED_BLOCK=0;
static final private int STATIC_TREES=1;
static final private int DYN_TREES=2;
// The three kinds of block type
static final private int Z_BINARY=0;
static final private int Z_ASCII=1;
static final private int Z_UNKNOWN=2;
static final private int Buf_size=8*2;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final private int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final private int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final private int REPZ_11_138=18;
static final private int MIN_MATCH=3;
static final private int MAX_MATCH=258;
static final private int MIN_LOOKAHEAD=(MAX_MATCH+MIN_MATCH+1);
static final private int MAX_BITS=15;
static final private int D_CODES=30;
static final private int BL_CODES=19;
static final private int LENGTH_CODES=29;
static final private int LITERALS=256;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
static final private int HEAP_SIZE=(2*L_CODES+1);
static final private int END_BLOCK=256;
ZStream strm; // pointer back to this zlib stream
int status; // as the name implies
byte[] pending_buf; // output still pending
int pending_buf_size; // size of pending_buf
int pending_out; // next pending byte to output to the stream
int pending; // nb of bytes in the pending buffer
int noheader; // suppress zlib header and adler32
byte data_type; // UNKNOWN, BINARY or ASCII
byte method; // STORED (for zip only) or DEFLATED
int last_flush; // value of flush param for previous deflate call
int w_size; // LZ77 window size (32K by default)
int w_bits; // log2(w_size) (8..16)
int w_mask; // w_size - 1
byte[] window;
// Sliding window. Input bytes are read into the second half of the window,
// and move to the first half later to keep a dictionary of at least wSize
// bytes. With this organization, matches are limited to a distance of
// wSize-MAX_MATCH bytes, but this ensures that IO is always
// performed with a length multiple of the block size. Also, it limits
// the window size to 64K, which is quite useful on MSDOS.
// To do: use the user input buffer as sliding window.
int window_size;
// Actual size of window: 2*wSize, except when the user input buffer
// is directly used as sliding window.
short[] prev;
// Link to older string with same hash index. To limit the size of this
// array to 64K, this link is maintained only for the last 32K strings.
// An index in this array is thus a window index modulo 32K.
short[] head; // Heads of the hash chains or NIL.
int ins_h; // hash index of string to be inserted
int hash_size; // number of elements in hash table
int hash_bits; // log2(hash_size)
int hash_mask; // hash_size-1
// Number of bits by which ins_h must be shifted at each input
// step. It must be such that after MIN_MATCH steps, the oldest
// byte no longer takes part in the hash key, that is:
// hash_shift * MIN_MATCH >= hash_bits
int hash_shift;
// Window position at the beginning of the current output block. Gets
// negative when the window is moved backwards.
int block_start;
int match_length; // length of best match
int prev_match; // previous match
int match_available; // set if previous match exists
int strstart; // start of string to insert
int match_start; // start of matching string
int lookahead; // number of valid bytes ahead in window
// Length of the best match at previous step. Matches not greater than this
// are discarded. This is used in the lazy match evaluation.
int prev_length;
// To speed up deflation, hash chains are never searched beyond this
// length. A higher limit improves compression ratio but degrades the speed.
int max_chain_length;
// Attempt to find a better match only when the current match is strictly
// smaller than this value. This mechanism is used only for compression
// levels >= 4.
int max_lazy_match;
// Insert new strings in the hash table only if the match length is not
// greater than this length. This saves time but degrades compression.
// max_insert_length is used only for compression levels <= 3.
int level; // compression level (1..9)
int strategy; // favor or force Huffman coding
// Use a faster search when the previous match is longer than this
int good_match;
// Stop searching when current match exceeds this
int nice_match;
short[] dyn_ltree; // literal and length tree
short[] dyn_dtree; // distance tree
short[] bl_tree; // Huffman tree for bit lengths
Tree l_desc=new Tree(); // desc for literal tree
Tree d_desc=new Tree(); // desc for distance tree
Tree bl_desc=new Tree(); // desc for bit length tree
// number of codes at each bit length for an optimal tree
short[] bl_count=new short[MAX_BITS+1];
// heap used to build the Huffman trees
int[] heap=new int[2*L_CODES+1];
int heap_len; // number of elements in the heap
int heap_max; // element of largest frequency
// The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
// The same heap array is used to build all trees.
// Depth of each subtree used as tie breaker for trees of equal frequency
byte[] depth=new byte[2*L_CODES+1];
int l_buf; // index for literals or lengths */
// Size of match buffer for literals/lengths. There are 4 reasons for
// limiting lit_bufsize to 64K:
// - frequencies can be kept in 16 bit counters
// - if compression is not successful for the first block, all input
// data is still in the window so we can still emit a stored block even
// when input comes from standard input. (This can also be done for
// all blocks if lit_bufsize is not greater than 32K.)
// - if compression is not successful for a file smaller than 64K, we can
// even emit a stored file instead of a stored block (saving 5 bytes).
// This is applicable only for zip (not gzip or zlib).
// - creating new Huffman trees less frequently may not provide fast
// adaptation to changes in the input data statistics. (Take for
// example a binary file with poorly compressible code followed by
// a highly compressible string table.) Smaller buffer sizes give
// fast adaptation but have of course the overhead of transmitting
// trees more frequently.
// - I can't count above 4
int lit_bufsize;
int last_lit; // running index in l_buf
// Buffer for distances. To simplify the code, d_buf and l_buf have
// the same number of elements. To use different lengths, an extra flag
// array would be necessary.
int d_buf; // index of pendig_buf
int opt_len; // bit length of current block with optimal trees
int static_len; // bit length of current block with static trees
int matches; // number of string matches in current block
int last_eob_len; // bit length of EOB code for last block
// Output buffer. bits are inserted starting at the bottom (least
// significant bits).
short bi_buf;
// Number of valid bits in bi_buf. All bits above the last valid bit
// are always zero.
int bi_valid;
Deflate(){
dyn_ltree=new short[HEAP_SIZE*2];
dyn_dtree=new short[(2*D_CODES+1)*2]; // distance tree
bl_tree=new short[(2*BL_CODES+1)*2]; // Huffman tree for bit lengths
}
void lm_init() {
window_size=2*w_size;
head[hash_size-1]=0;
for(int i=0; i<hash_size-1; i++){
head[i]=0;
}
// Set the default configuration parameters:
max_lazy_match = Deflate.config_table[level].max_lazy;
good_match = Deflate.config_table[level].good_length;
nice_match = Deflate.config_table[level].nice_length;
max_chain_length = Deflate.config_table[level].max_chain;
strstart = 0;
block_start = 0;
lookahead = 0;
match_length = prev_length = MIN_MATCH-1;
match_available = 0;
ins_h = 0;
}
// Initialize the tree data structures for a new zlib stream.
void tr_init(){
l_desc.dyn_tree = dyn_ltree;
l_desc.stat_desc = StaticTree.static_l_desc;
d_desc.dyn_tree = dyn_dtree;
d_desc.stat_desc = StaticTree.static_d_desc;
bl_desc.dyn_tree = bl_tree;
bl_desc.stat_desc = StaticTree.static_bl_desc;
bi_buf = 0;
bi_valid = 0;
last_eob_len = 8; // enough lookahead for inflate
// Initialize the first block of the first file:
init_block();
}
void init_block(){
// Initialize the trees.
for(int i = 0; i < L_CODES; i++) dyn_ltree[i*2] = 0;
for(int i= 0; i < D_CODES; i++) dyn_dtree[i*2] = 0;
for(int i= 0; i < BL_CODES; i++) bl_tree[i*2] = 0;
dyn_ltree[END_BLOCK*2] = 1;
opt_len = static_len = 0;
last_lit = matches = 0;
}
// Restore the heap property by moving down the tree starting at node k,
// exchanging a node with the smallest of its two sons if necessary, stopping
// when the heap property is re-established (each father smaller than its
// two sons).
void pqdownheap(short[] tree, // the tree to restore
int k // node to move down
){
int v = heap[k];
int j = k << 1; // left son of k
while (j <= heap_len) {
// Set j to the smallest of the two sons:
if (j < heap_len &&
smaller(tree, heap[j+1], heap[j], depth)){
j++;
}
// Exit if v is smaller than both sons
if(smaller(tree, v, heap[j], depth)) break;
// Exchange v with the smallest son
heap[k]=heap[j]; k = j;
// And continue down the tree, setting j to the left son of k
j <<= 1;
}
heap[k] = v;
}
static boolean smaller(short[] tree, int n, int m, byte[] depth){
short tn2=tree[n*2];
short tm2=tree[m*2];
return (tn2<tm2 ||
(tn2==tm2 && depth[n] <= depth[m]));
}
// Scan a literal or distance tree to determine the frequencies of the codes
// in the bit length tree.
void scan_tree (short[] tree,// the tree to be scanned
int max_code // and its largest code of non zero frequency
){
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
int nextlen = tree[0*2+1]; // length of next code
int count = 0; // repeat count of the current code
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
if (nextlen == 0){ max_count = 138; min_count = 3; }
tree[(max_code+1)*2+1] = (short)0xffff; // guard
for(n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[(n+1)*2+1];
if(++count < max_count && curlen == nextlen) {
continue;
}
else if(count < min_count) {
bl_tree[curlen*2] += count;
}
else if(curlen != 0) {
if(curlen != prevlen) bl_tree[curlen*2]++;
bl_tree[REP_3_6*2]++;
}
else if(count <= 10) {
bl_tree[REPZ_3_10*2]++;
}
else{
bl_tree[REPZ_11_138*2]++;
}
count = 0; prevlen = curlen;
if(nextlen == 0) {
max_count = 138; min_count = 3;
}
else if(curlen == nextlen) {
max_count = 6; min_count = 3;
}
else{
max_count = 7; min_count = 4;
}
}
}
// Construct the Huffman tree for the bit lengths and return the index in
// bl_order of the last bit length code to send.
int build_bl_tree(){
int max_blindex; // index of last bit length code of non zero freq
// Determine the bit length frequencies for literal and distance trees
scan_tree(dyn_ltree, l_desc.max_code);
scan_tree(dyn_dtree, d_desc.max_code);
// Build the bit length tree:
bl_desc.build_tree(this);
// opt_len now includes the length of the tree representations, except
// the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
// Determine the number of bit length codes to send. The pkzip format
// requires that at least 4 bit length codes be sent. (appnote.txt says
// 3 but the actual value used is 4.)
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (bl_tree[Tree.bl_order[max_blindex]*2+1] != 0) break;
}
// Update opt_len to include the bit length tree and counts
opt_len += 3*(max_blindex+1) + 5+5+4;
return max_blindex;
}
// Send the header for a block using dynamic Huffman trees: the counts, the
// lengths of the bit length codes, the literal tree and the distance tree.
// IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
void send_all_trees(int lcodes, int dcodes, int blcodes){
int rank; // index in bl_order
send_bits(lcodes-257, 5); // not +255 as stated in appnote.txt
send_bits(dcodes-1, 5);
send_bits(blcodes-4, 4); // not -3 as stated in appnote.txt
for (rank = 0; rank < blcodes; rank++) {
send_bits(bl_tree[Tree.bl_order[rank]*2+1], 3);
}
send_tree(dyn_ltree, lcodes-1); // literal tree
send_tree(dyn_dtree, dcodes-1); // distance tree
}
// Send a literal or distance tree in compressed form, using the codes in
// bl_tree.
void send_tree (short[] tree,// the tree to be sent
int max_code // and its largest code of non zero frequency
){
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
int nextlen = tree[0*2+1]; // length of next code
int count = 0; // repeat count of the current code
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
if (nextlen == 0){ max_count = 138; min_count = 3; }
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[(n+1)*2+1];
if(++count < max_count && curlen == nextlen) {
continue;
}
else if(count < min_count) {
do { send_code(curlen, bl_tree); } while (--count != 0);
}
else if(curlen != 0){
if(curlen != prevlen){
send_code(curlen, bl_tree); count--;
}
send_code(REP_3_6, bl_tree);
send_bits(count-3, 2);
}
else if(count <= 10){
send_code(REPZ_3_10, bl_tree);
send_bits(count-3, 3);
}
else{
send_code(REPZ_11_138, bl_tree);
send_bits(count-11, 7);
}
count = 0; prevlen = curlen;
if(nextlen == 0){
max_count = 138; min_count = 3;
}
else if(curlen == nextlen){
max_count = 6; min_count = 3;
}
else{
max_count = 7; min_count = 4;
}
}
}
// Output a byte on the stream.
// IN assertion: there is enough room in pending_buf.
final void put_byte(byte[] p, int start, int len){
System.arraycopy(p, start, pending_buf, pending, len);
pending+=len;
}
final void put_byte(byte c){
pending_buf[pending++]=c;
}
final void put_short(int w) {
put_byte((byte)(w/*&0xff*/));
put_byte((byte)(w>>>8));
}
final void putShortMSB(int b){
put_byte((byte)(b>>8));
put_byte((byte)(b/*&0xff*/));
}
final void send_code(int c, short[] tree){
int c2=c*2;
send_bits((tree[c2]&0xffff), (tree[c2+1]&0xffff));
}
void send_bits(int value, int length){
int len = length;
if (bi_valid > (int)Buf_size - len) {
int val = value;
// bi_buf |= (val << bi_valid);
bi_buf |= ((val << bi_valid)&0xffff);
put_short(bi_buf);
bi_buf = (short)(val >>> (Buf_size - bi_valid));
bi_valid += len - Buf_size;
} else {
// bi_buf |= (value) << bi_valid;
bi_buf |= (((value) << bi_valid)&0xffff);
bi_valid += len;
}
}
// Send one empty static block to give enough lookahead for inflate.
// This takes 10 bits, of which 7 may remain in the bit buffer.
// The current inflate code requires 9 bits of lookahead. If the
// last two codes for the previous block (real code plus EOB) were coded
// on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
// the last real code. In this case we send two empty static blocks instead
// of one. (There are no problems if the previous block is stored or fixed.)
// To simplify the code, we assume the worst case of last real code encoded
// on one bit only.
void _tr_align(){
send_bits(STATIC_TREES<<1, 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
// Of the 10 bits for the empty block, we have already sent
// (10 - bi_valid) bits. The lookahead for the last real code (before
// the EOB of the previous block) was thus at least one plus the length
// of the EOB plus what we have just sent of the empty static block.
if (1 + last_eob_len + 10 - bi_valid < 9) {
send_bits(STATIC_TREES<<1, 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
}
last_eob_len = 7;
}
// Save the match info and tally the frequency counts. Return true if
// the current block must be flushed.
boolean _tr_tally (int dist, // distance of matched string
int lc // match length-MIN_MATCH or unmatched char (if dist==0)
){
pending_buf[d_buf+last_lit*2] = (byte)(dist>>>8);
pending_buf[d_buf+last_lit*2+1] = (byte)dist;
pending_buf[l_buf+last_lit] = (byte)lc; last_lit++;
if (dist == 0) {
// lc is the unmatched char
dyn_ltree[lc*2]++;
}
else {
matches++;
// Here, lc is the match length - MIN_MATCH
dist--; // dist = match distance - 1
dyn_ltree[(Tree._length_code[lc]+LITERALS+1)*2]++;
dyn_dtree[Tree.d_code(dist)*2]++;
}
if ((last_lit & 0x1fff) == 0 && level > 2) {
// Compute an upper bound for the compressed length
int out_length = last_lit*8;
int in_length = strstart - block_start;
int dcode;
for (dcode = 0; dcode < D_CODES; dcode++) {
out_length += (int)dyn_dtree[dcode*2] *
(5L+Tree.extra_dbits[dcode]);
}
out_length >>>= 3;
if ((matches < (last_lit/2)) && out_length < in_length/2) return true;
}
return (last_lit == lit_bufsize-1);
// We avoid equality with lit_bufsize because of wraparound at 64K
// on 16 bit machines and because stored blocks are restricted to
// 64K-1 bytes.
}
// Send the block data compressed using the given Huffman trees
void compress_block(short[] ltree, short[] dtree){
int dist; // distance of matched string
int lc; // match length or unmatched char (if dist == 0)
int lx = 0; // running index in l_buf
int code; // the code to send
int extra; // number of extra bits to send
if (last_lit != 0){
do{
dist=((pending_buf[d_buf+lx*2]<<8)&0xff00)|
(pending_buf[d_buf+lx*2+1]&0xff);
lc=(pending_buf[l_buf+lx])&0xff; lx++;
if(dist == 0){
send_code(lc, ltree); // send a literal byte
}
else{
// Here, lc is the match length - MIN_MATCH
code = Tree._length_code[lc];
send_code(code+LITERALS+1, ltree); // send the length code
extra = Tree.extra_lbits[code];
if(extra != 0){
lc -= Tree.base_length[code];
send_bits(lc, extra); // send the extra length bits
}
dist--; // dist is now the match distance - 1
code = Tree.d_code(dist);
send_code(code, dtree); // send the distance code
extra = Tree.extra_dbits[code];
if (extra != 0) {
dist -= Tree.base_dist[code];
send_bits(dist, extra); // send the extra distance bits
}
} // literal or match pair ?
// Check that the overlay between pending_buf and d_buf+l_buf is ok:
}
while (lx < last_lit);
}
send_code(END_BLOCK, ltree);
last_eob_len = ltree[END_BLOCK*2+1];
}
// Set the data type to ASCII or BINARY, using a crude approximation:
// binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
// IN assertion: the fields freq of dyn_ltree are set and the total of all
// frequencies does not exceed 64K (to fit in an int on 16 bit machines).
void set_data_type(){
int n = 0;
int ascii_freq = 0;
int bin_freq = 0;
while(n<7){ bin_freq += dyn_ltree[n*2]; n++;}
while(n<128){ ascii_freq += dyn_ltree[n*2]; n++;}
while(n<LITERALS){ bin_freq += dyn_ltree[n*2]; n++;}
data_type=(byte)(bin_freq > (ascii_freq >>> 2) ? Z_BINARY : Z_ASCII);
}
// Flush the bit buffer, keeping at most 7 bits in it.
void bi_flush(){
if (bi_valid == 16) {
put_short(bi_buf);
bi_buf=0;
bi_valid=0;
}
else if (bi_valid >= 8) {
put_byte((byte)bi_buf);
bi_buf>>>=8;
bi_valid-=8;
}
}
// Flush the bit buffer and align the output on a byte boundary
void bi_windup(){
if (bi_valid > 8) {
put_short(bi_buf);
} else if (bi_valid > 0) {
put_byte((byte)bi_buf);
}
bi_buf = 0;
bi_valid = 0;
}
// Copy a stored block, storing first the length and its
// one's complement if requested.
void copy_block(int buf, // the input data
int len, // its length
boolean header // true if block header must be written
){
int index=0;
bi_windup(); // align on byte boundary
last_eob_len = 8; // enough lookahead for inflate
if (header) {
put_short((short)len);
put_short((short)~len);
}
// while(len--!=0) {
// put_byte(window[buf+index]);
// index++;
// }
put_byte(window, buf, len);
}
void flush_block_only(boolean eof){
_tr_flush_block(block_start>=0 ? block_start : -1,
strstart-block_start,
eof);
block_start=strstart;
strm.flush_pending();
}
// Copy without compression as much as possible from the input stream, return
// the current block state.
// This function does not insert new strings in the dictionary since
// uncompressible data is probably not useful. This function is used
// only for the level=0 compression option.
// NOTE: this function should be optimized to avoid extra copying from
// window to pending_buf.
int deflate_stored(int flush){
// Stored blocks are limited to 0xffff bytes, pending_buf is limited
// to pending_buf_size, and each stored block has a 5 byte header:
int max_block_size = 0xffff;
int max_start;
if(max_block_size > pending_buf_size - 5) {
max_block_size = pending_buf_size - 5;
}
// Copy as much as possible from input to output:
while(true){
// Fill the window as much as possible:
if(lookahead<=1){
fill_window();
if(lookahead==0 && flush==Z_NO_FLUSH) return NeedMore;
if(lookahead==0) break; // flush the current block
}
strstart+=lookahead;
lookahead=0;
// Emit a stored block if pending_buf will be full:
max_start=block_start+max_block_size;
if(strstart==0|| strstart>=max_start) {
// strstart == 0 is possible when wraparound on 16-bit machine
lookahead = (int)(strstart-max_start);
strstart = (int)max_start;
flush_block_only(false);
if(strm.avail_out==0) return NeedMore;
}
// Flush if we may have to slide, otherwise block_start may become
// negative and the data will be gone:
if(strstart-block_start >= w_size-MIN_LOOKAHEAD) {
flush_block_only(false);
if(strm.avail_out==0) return NeedMore;
}
}
flush_block_only(flush == Z_FINISH);
if(strm.avail_out==0)
return (flush == Z_FINISH) ? FinishStarted : NeedMore;
return flush == Z_FINISH ? FinishDone : BlockDone;
}
// Send a stored block
void _tr_stored_block(int buf, // input block
int stored_len, // length of input block
boolean eof // true if this is the last block for a file
){
send_bits((STORED_BLOCK<<1)+(eof?1:0), 3); // send block type
copy_block(buf, stored_len, true); // with header
}
// Determine the best encoding for the current block: dynamic trees, static
// trees or store, and output the encoded block to the zip file.
void _tr_flush_block(int buf, // input block, or NULL if too old
int stored_len, // length of input block
boolean eof // true if this is the last block for a file
) {
int opt_lenb, static_lenb;// opt_len and static_len in bytes
int max_blindex = 0; // index of last bit length code of non zero freq
// Build the Huffman trees unless a stored block is forced
if(level > 0) {
// Check if the file is ascii or binary
if(data_type == Z_UNKNOWN) set_data_type();
// Construct the literal and distance trees
l_desc.build_tree(this);
d_desc.build_tree(this);
// At this point, opt_len and static_len are the total bit lengths of
// the compressed block data, excluding the tree representations.
// Build the bit length tree for the above two trees, and get the index
// in bl_order of the last bit length code to send.
max_blindex=build_bl_tree();
// Determine the best encoding. Compute first the block length in bytes
opt_lenb=(opt_len+3+7)>>>3;
static_lenb=(static_len+3+7)>>>3;
if(static_lenb<=opt_lenb) opt_lenb=static_lenb;
}
else {
opt_lenb=static_lenb=stored_len+5; // force a stored block
}
if(stored_len+4<=opt_lenb && buf != -1){
// 4: two words for the lengths
// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
// Otherwise we can't have processed more than WSIZE input bytes since
// the last block flush, because compression would have been
// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
// transform a block into a stored block.
_tr_stored_block(buf, stored_len, eof);
}
else if(static_lenb == opt_lenb){
send_bits((STATIC_TREES<<1)+(eof?1:0), 3);
compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
}
else{
send_bits((DYN_TREES<<1)+(eof?1:0), 3);
send_all_trees(l_desc.max_code+1, d_desc.max_code+1, max_blindex+1);
compress_block(dyn_ltree, dyn_dtree);
}
// The above check is made mod 2^32, for files larger than 512 MB
// and uLong implemented on 32 bits.
init_block();
if(eof){
bi_windup();
}
}
// Fill the window when the lookahead becomes insufficient.
// Updates strstart and lookahead.
//
// IN assertion: lookahead < MIN_LOOKAHEAD
// OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
// At least one byte has been read, or avail_in == 0; reads are
// performed for at least two bytes (required for the zip translate_eol
// option -- not supported here).
void fill_window(){
int n, m;
int p;
int more; // Amount of free space at the end of the window.
do{
more = (window_size-lookahead-strstart);
// Deal with !@#$% 64K limit:
if(more==0 && strstart==0 && lookahead==0){
more = w_size;
}
else if(more==-1) {
// Very unlikely, but possible on 16 bit machine if strstart == 0
// and lookahead == 1 (input done one byte at time)
more--;
// If the window is almost full and there is insufficient lookahead,
// move the upper half to the lower one to make room in the upper half.
}
else if(strstart >= w_size+ w_size-MIN_LOOKAHEAD) {
System.arraycopy(window, w_size, window, 0, w_size);
match_start-=w_size;
strstart-=w_size; // we now have strstart >= MAX_DIST
block_start-=w_size;
// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage). We slide even when level == 0
// to keep the hash table consistent if we switch back to level > 0
// later. (Using level 0 permanently is not an optimal usage of
// zlib, so we don't care about this pathological case.)
n = hash_size;
p=n;
do {
m = (head[--p]&0xffff);
head[p]=(m>=w_size ? (short)(m-w_size) : 0);
}
while (--n != 0);
n = w_size;
p = n;
do {
m = (prev[--p]&0xffff);
prev[p] = (m >= w_size ? (short)(m-w_size) : 0);
// If n is not on any hash chain, prev[n] is garbage but
// its value will never be used.
}
while (--n!=0);
more += w_size;
}
if (strm.avail_in == 0) return;
// If there was no sliding:
// strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
// more == window_size - lookahead - strstart
// => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
// => more >= window_size - 2*WSIZE + 2
// In the BIG_MEM or MMAP case (not yet supported),
// window_size == input_size + MIN_LOOKAHEAD &&
// strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
// Otherwise, window_size == 2*WSIZE so more >= 2.
// If there was sliding, more >= WSIZE. So in all cases, more >= 2.
n = strm.read_buf(window, strstart + lookahead, more);
lookahead += n;
// Initialize the hash value now that we have some input:
if(lookahead >= MIN_MATCH) {
ins_h = window[strstart]&0xff;
ins_h=(((ins_h)<<hash_shift)^(window[strstart+1]&0xff))&hash_mask;
}
// If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
// but this is not important since only literal bytes will be emitted.
}
while (lookahead < MIN_LOOKAHEAD && strm.avail_in != 0);
}
// Compress as much as possible from the input stream, return the current
// block state.
// This function does not perform lazy evaluation of matches and inserts
// new strings in the dictionary only for unmatched strings or for short
// matches. It is used only for the fast compression options.
int deflate_fast(int flush){
// short hash_head = 0; // head of the hash chain
int hash_head = 0; // head of the hash chain
boolean bflush; // set if current block must be flushed
while(true){
// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
if(lookahead < MIN_LOOKAHEAD){
fill_window();
if(lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH){
return NeedMore;
}
if(lookahead == 0) break; // flush the current block
}
// Insert the string window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
if(lookahead >= MIN_MATCH){
ins_h=(((ins_h)<<hash_shift)^(window[(strstart)+(MIN_MATCH-1)]&0xff))&hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head=(head[ins_h]&0xffff);
prev[strstart&w_mask]=head[ins_h];
head[ins_h]=(short)strstart;
}
// Find the longest match, discarding those <= prev_length.
// At this point we have always match_length < MIN_MATCH
if(hash_head!=0L &&
((strstart-hash_head)&0xffff) <= w_size-MIN_LOOKAHEAD
){
// To simplify the code, we prevent matches with the string
// of window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
if(strategy != Z_HUFFMAN_ONLY){
match_length=longest_match (hash_head);
}
// longest_match() sets match_start
}
if(match_length>=MIN_MATCH){
// check_match(strstart, match_start, match_length);
bflush=_tr_tally(strstart-match_start, match_length-MIN_MATCH);
lookahead -= match_length;
// Insert new strings in the hash table only if the match length
// is not too large. This saves time but degrades compression.
if(match_length <= max_lazy_match &&
lookahead >= MIN_MATCH) {
match_length--; // string at strstart already in hash table
do{
strstart++;
ins_h=((ins_h<<hash_shift)^(window[(strstart)+(MIN_MATCH-1)]&0xff))&hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head=(head[ins_h]&0xffff);
prev[strstart&w_mask]=head[ins_h];
head[ins_h]=(short)strstart;
// strstart never exceeds WSIZE-MAX_MATCH, so there are
// always MIN_MATCH bytes ahead.
}
while (--match_length != 0);
strstart++;
}
else{
strstart += match_length;
match_length = 0;
ins_h = window[strstart]&0xff;
ins_h=(((ins_h)<<hash_shift)^(window[strstart+1]&0xff))&hash_mask;
// If lookahead < MIN_MATCH, ins_h is garbage, but it does not
// matter since it will be recomputed at next deflate call.
}
}
else {
// No match, output a literal byte
bflush=_tr_tally(0, window[strstart]&0xff);
lookahead--;
strstart++;
}
if (bflush){
flush_block_only(false);
if(strm.avail_out==0) return NeedMore;
}
}
flush_block_only(flush == Z_FINISH);
if(strm.avail_out==0){
if(flush == Z_FINISH) return FinishStarted;
else return NeedMore;
}
return flush==Z_FINISH ? FinishDone : BlockDone;
}
// Same as above, but achieves better compression. We use a lazy
// evaluation for matches: a match is finally adopted only if there is
// no better match at the next window position.
int deflate_slow(int flush){
// short hash_head = 0; // head of hash chain
int hash_head = 0; // head of hash chain
boolean bflush; // set if current block must be flushed
// Process the input block.
while(true){
// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
if (lookahead < MIN_LOOKAHEAD) {
fill_window();
if(lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return NeedMore;
}
if(lookahead == 0) break; // flush the current block
}
// Insert the string window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
if(lookahead >= MIN_MATCH) {
ins_h=(((ins_h)<<hash_shift)^(window[(strstart)+(MIN_MATCH-1)]&0xff)) & hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head=(head[ins_h]&0xffff);
prev[strstart&w_mask]=head[ins_h];
head[ins_h]=(short)strstart;
}
// Find the longest match, discarding those <= prev_length.
prev_length = match_length; prev_match = match_start;
match_length = MIN_MATCH-1;
if (hash_head != 0 && prev_length < max_lazy_match &&
((strstart-hash_head)&0xffff) <= w_size-MIN_LOOKAHEAD
){
// To simplify the code, we prevent matches with the string
// of window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
if(strategy != Z_HUFFMAN_ONLY) {
match_length = longest_match(hash_head);
}
// longest_match() sets match_start
if (match_length <= 5 && (strategy == Z_FILTERED ||
(match_length == MIN_MATCH &&
strstart - match_start > 4096))) {
// If prev_match is also MIN_MATCH, match_start is garbage
// but we will ignore the current match anyway.
match_length = MIN_MATCH-1;
}
}
// If there was a match at the previous step and the current
// match is not better, output the previous match:
if(prev_length >= MIN_MATCH && match_length <= prev_length) {
int max_insert = strstart + lookahead - MIN_MATCH;
// Do not insert strings in hash table beyond this.
// check_match(strstart-1, prev_match, prev_length);
bflush=_tr_tally(strstart-1-prev_match, prev_length - MIN_MATCH);
// Insert in hash table all strings up to the end of the match.
// strstart-1 and strstart are already inserted. If there is not
// enough lookahead, the last two strings are not inserted in
// the hash table.
lookahead -= prev_length-1;
prev_length -= 2;
do{
if(++strstart <= max_insert) {
ins_h=(((ins_h)<<hash_shift)^(window[(strstart)+(MIN_MATCH-1)]&0xff))&hash_mask;
//prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head=(head[ins_h]&0xffff);
prev[strstart&w_mask]=head[ins_h];
head[ins_h]=(short)strstart;
}
}
while(--prev_length != 0);
match_available = 0;
match_length = MIN_MATCH-1;
strstart++;
if (bflush){
flush_block_only(false);
if(strm.avail_out==0) return NeedMore;
}
} else if (match_available!=0) {
// If there was no match at the previous position, output a
// single literal. If there was a match but the current match
// is longer, truncate the previous match to a single literal.
bflush=_tr_tally(0, window[strstart-1]&0xff);
if (bflush) {
flush_block_only(false);
}
strstart++;
lookahead--;
if(strm.avail_out == 0) return NeedMore;
} else {
// There is no previous match to compare with, wait for
// the next step to decide.
match_available = 1;
strstart++;
lookahead--;
}
}
if(match_available!=0) {
bflush=_tr_tally(0, window[strstart-1]&0xff);
match_available = 0;
}
flush_block_only(flush == Z_FINISH);
if(strm.avail_out==0){
if(flush == Z_FINISH) return FinishStarted;
else return NeedMore;
}
return flush == Z_FINISH ? FinishDone : BlockDone;
}
int longest_match(int cur_match){
int chain_length = max_chain_length; // max hash chain length
int scan = strstart; // current string
int match; // matched string
int len; // length of current match
int best_len = prev_length; // best match length so far
int limit = strstart>(w_size-MIN_LOOKAHEAD) ?
strstart-(w_size-MIN_LOOKAHEAD) : 0;
int nice_match=this.nice_match;
// Stop when cur_match becomes <= limit. To simplify the code,
// we prevent matches with the string of window index 0.
int wmask = w_mask;
int strend = strstart + MAX_MATCH;
byte scan_end1 = window[scan+best_len-1];
byte scan_end = window[scan+best_len];
// The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
// It is easy to get rid of this optimization if necessary.
// Do not waste too much time if we already have a good match:
if (prev_length >= good_match) {
chain_length >>= 2;
}
// Do not look for matches beyond the end of the input. This is necessary
// to make deflate deterministic.
if (nice_match > lookahead) nice_match = lookahead;
do {
match = cur_match;
// Skip to next match if the match length cannot increase
// or if the match length is less than 2:
if (window[match+best_len] != scan_end ||
window[match+best_len-1] != scan_end1 ||
window[match] != window[scan] ||
window[++match] != window[scan+1]) continue;
// The check at best_len-1 can be removed because it will be made
// again later. (This heuristic is not always a win.)
// It is not necessary to compare scan[2] and match[2] since they
// are always equal when the other bytes match, given that
// the hash keys are equal and that HASH_BITS >= 8.
scan += 2; match++;
// We check for insufficient lookahead only every 8th comparison;
// the 256th check will be made at strstart+258.
do {
} while (window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
scan < strend);
len = MAX_MATCH - (int)(strend - scan);
scan = strend - MAX_MATCH;
if(len>best_len) {
match_start = cur_match;
best_len = len;
if (len >= nice_match) break;
scan_end1 = window[scan+best_len-1];
scan_end = window[scan+best_len];
}
} while ((cur_match = (prev[cur_match & wmask]&0xffff)) > limit
&& --chain_length != 0);
if (best_len <= lookahead) return best_len;
return lookahead;
}
int deflateInit(ZStream strm, int level, int bits){
return deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY);
}
int deflateInit(ZStream strm, int level){
return deflateInit(strm, level, MAX_WBITS);
}
int deflateInit2(ZStream strm, int level, int method, int windowBits,
int memLevel, int strategy){
int noheader = 0;
// byte[] my_version=ZLIB_VERSION;
//
// if (version == null || version[0] != my_version[0]
// || stream_size != sizeof(z_stream)) {
// return Z_VERSION_ERROR;
// }
strm.msg = null;
if (level == Z_DEFAULT_COMPRESSION) level = 6;
if (windowBits < 0) { // undocumented feature: suppress zlib header
noheader = 1;
windowBits = -windowBits;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL ||
method != Z_DEFLATED ||
windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR;
}
strm.dstate = (Deflate)this;
this.noheader = noheader;
w_bits = windowBits;
w_size = 1 << w_bits;
w_mask = w_size - 1;
hash_bits = memLevel + 7;
hash_size = 1 << hash_bits;
hash_mask = hash_size - 1;
hash_shift = ((hash_bits+MIN_MATCH-1)/MIN_MATCH);
window = new byte[w_size*2];
prev = new short[w_size];
head = new short[hash_size];
lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
// We overlay pending_buf and d_buf+l_buf. This works since the average
// output size for (length,distance) codes is <= 24 bits.
pending_buf = new byte[lit_bufsize*4];
pending_buf_size = lit_bufsize*4;
d_buf = lit_bufsize/2;
l_buf = (1+2)*lit_bufsize;
this.level = level;
//System.out.println("level="+level);
this.strategy = strategy;
this.method = (byte)method;
return deflateReset(strm);
}
int deflateReset(ZStream strm){
strm.total_in = strm.total_out = 0;
strm.msg = null; //
strm.data_type = Z_UNKNOWN;
pending = 0;
pending_out = 0;
if(noheader < 0) {
noheader = 0; // was set to -1 by deflate(..., Z_FINISH);
}
status = (noheader!=0) ? BUSY_STATE : INIT_STATE;
strm.adler=strm._adler.adler32(0, null, 0, 0);
last_flush = Z_NO_FLUSH;
tr_init();
lm_init();
return Z_OK;
}
int deflateEnd(){
if(status!=INIT_STATE && status!=BUSY_STATE && status!=FINISH_STATE){
return Z_STREAM_ERROR;
}
// Deallocate in reverse order of allocations:
pending_buf=null;
head=null;
prev=null;
window=null;
// free
// dstate=null;
return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
}
int deflateParams(ZStream strm, int _level, int _strategy){
int err=Z_OK;
if(_level == Z_DEFAULT_COMPRESSION){
_level = 6;
}
if(_level < 0 || _level > 9 ||
_strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR;
}
if(config_table[level].func!=config_table[_level].func &&
strm.total_in != 0) {
// Flush the last buffer:
err = strm.deflate(Z_PARTIAL_FLUSH);
}
if(level != _level) {
level = _level;
max_lazy_match = config_table[level].max_lazy;
good_match = config_table[level].good_length;
nice_match = config_table[level].nice_length;
max_chain_length = config_table[level].max_chain;
}
strategy = _strategy;
return err;
}
int deflateSetDictionary (ZStream strm, byte[] dictionary, int dictLength){
int length = dictLength;
int index=0;
if(dictionary == null || status != INIT_STATE)
return Z_STREAM_ERROR;
strm.adler=strm._adler.adler32(strm.adler, dictionary, 0, dictLength);
if(length < MIN_MATCH) return Z_OK;
if(length > w_size-MIN_LOOKAHEAD){
length = w_size-MIN_LOOKAHEAD;
index=dictLength-length; // use the tail of the dictionary
}
System.arraycopy(dictionary, index, window, 0, length);
strstart = length;
block_start = length;
// Insert all strings in the hash table (except for the last two bytes).
// s->lookahead stays null, so s->ins_h will be recomputed at the next
// call of fill_window.
ins_h = window[0]&0xff;
ins_h=(((ins_h)<<hash_shift)^(window[1]&0xff))&hash_mask;
for(int n=0; n<=length-MIN_MATCH; n++){
ins_h=(((ins_h)<<hash_shift)^(window[(n)+(MIN_MATCH-1)]&0xff))&hash_mask;
prev[n&w_mask]=head[ins_h];
head[ins_h]=(short)n;
}
return Z_OK;
}
int deflate(ZStream strm, int flush){
int old_flush;
if(flush>Z_FINISH || flush<0){
return Z_STREAM_ERROR;
}
if(strm.next_out == null ||
(strm.next_in == null && strm.avail_in != 0) ||
(status == FINISH_STATE && flush != Z_FINISH)) {
strm.msg=z_errmsg[Z_NEED_DICT-(Z_STREAM_ERROR)];
return Z_STREAM_ERROR;
}
if(strm.avail_out == 0){
strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)];
return Z_BUF_ERROR;
}
this.strm = strm; // just in case
old_flush = last_flush;
last_flush = flush;
// Write the zlib header
if(status == INIT_STATE) {
int header = (Z_DEFLATED+((w_bits-8)<<4))<<8;
int level_flags=((level-1)&0xff)>>1;
if(level_flags>3) level_flags=3;
header |= (level_flags<<6);
if(strstart!=0) header |= PRESET_DICT;
header+=31-(header % 31);
status=BUSY_STATE;
putShortMSB(header);
// Save the adler32 of the preset dictionary:
if(strstart!=0){
putShortMSB((int)(strm.adler>>>16));
putShortMSB((int)(strm.adler&0xffff));
}
strm.adler=strm._adler.adler32(0, null, 0, 0);
}
// Flush as much pending output as possible
if(pending != 0) {
strm.flush_pending();
if(strm.avail_out == 0) {
//System.out.println(" avail_out==0");
// Since avail_out is 0, deflate will be called again with
// more output space, but possibly with both pending and
// avail_in equal to zero. There won't be anything to do,
// but this is not an error situation so make sure we
// return OK instead of BUF_ERROR at next call of deflate:
last_flush = -1;
return Z_OK;
}
// Make sure there is something to do and avoid duplicate consecutive
// flushes. For repeated and useless calls with Z_FINISH, we keep
// returning Z_STREAM_END instead of Z_BUFF_ERROR.
}
else if(strm.avail_in==0 && flush <= old_flush &&
flush != Z_FINISH) {
strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)];
return Z_BUF_ERROR;
}
// User must not provide more input after the first FINISH:
if(status == FINISH_STATE && strm.avail_in != 0) {
strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)];
return Z_BUF_ERROR;
}
// Start a new block or continue the current one.
if(strm.avail_in!=0 || lookahead!=0 ||
(flush != Z_NO_FLUSH && status != FINISH_STATE)) {
int bstate=-1;
switch(config_table[level].func){
case STORED:
bstate = deflate_stored(flush);
break;
case FAST:
bstate = deflate_fast(flush);
break;
case SLOW:
bstate = deflate_slow(flush);
break;
default:
}
if (bstate==FinishStarted || bstate==FinishDone) {
status = FINISH_STATE;
}
if (bstate==NeedMore || bstate==FinishStarted) {
if(strm.avail_out == 0) {
last_flush = -1; // avoid BUF_ERROR next call, see above
}
return Z_OK;
// If flush != Z_NO_FLUSH && avail_out == 0, the next call
// of deflate should use the same flush parameter to make sure
// that the flush is complete. So we don't have to output an
// empty block here, this will be done at next call. This also
// ensures that for a very small output buffer, we emit at most
// one empty block.
}
if (bstate==BlockDone) {
if(flush == Z_PARTIAL_FLUSH) {
_tr_align();
}
else { // FULL_FLUSH or SYNC_FLUSH
_tr_stored_block(0, 0, false);
// For a full flush, this empty block will be recognized
// as a special marker by inflate_sync().
if(flush == Z_FULL_FLUSH) {
//state.head[s.hash_size-1]=0;
for(int i=0; i<hash_size/*-1*/; i++) // forget history
head[i]=0;
}
}
strm.flush_pending();
if(strm.avail_out == 0) {
last_flush = -1; // avoid BUF_ERROR at next call, see above
return Z_OK;
}
}
}
if(flush!=Z_FINISH) return Z_OK;
if(noheader!=0) return Z_STREAM_END;
// Write the zlib trailer (adler32)
putShortMSB((int)(strm.adler>>>16));
putShortMSB((int)(strm.adler&0xffff));
strm.flush_pending();
// If avail_out is zero, the application will call deflate again
// to flush the rest.
noheader = -1; // write the trailer only once!
return pending != 0 ? Z_OK : Z_STREAM_END;
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/Deflate.java
|
Java
|
asf20
| 54,205
|
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2001 Lapo Luchini.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS
OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
import java.io.*;
public class ZInputStream extends FilterInputStream {
protected ZStream z=new ZStream();
protected int bufsize=512;
protected int flush=JZlib.Z_NO_FLUSH;
protected byte[] buf=new byte[bufsize],
buf1=new byte[1];
protected boolean compress;
protected InputStream in=null;
public ZInputStream(InputStream in) {
this(in, false);
}
public ZInputStream(InputStream in, boolean nowrap) {
super(in);
this.in=in;
z.inflateInit(nowrap);
compress=false;
z.next_in=buf;
z.next_in_index=0;
z.avail_in=0;
}
public ZInputStream(InputStream in, int level) {
super(in);
this.in=in;
z.deflateInit(level);
compress=true;
z.next_in=buf;
z.next_in_index=0;
z.avail_in=0;
}
/*public int available() throws IOException {
return inf.finished() ? 0 : 1;
}*/
public int read() throws IOException {
if(read(buf1, 0, 1)==-1)
return(-1);
return(buf1[0]&0xFF);
}
private boolean nomoreinput=false;
public int read(byte[] b, int off, int len) throws IOException {
if(len==0)
return(0);
int err;
z.next_out=b;
z.next_out_index=off;
z.avail_out=len;
do {
if((z.avail_in==0)&&(!nomoreinput)) { // if buffer is empty and more input is avaiable, refill it
z.next_in_index=0;
z.avail_in=in.read(buf, 0, bufsize);//(bufsize<z.avail_out ? bufsize : z.avail_out));
if(z.avail_in==-1) {
z.avail_in=0;
nomoreinput=true;
}
}
if(compress)
err=z.deflate(flush);
else
err=z.inflate(flush);
if(nomoreinput&&(err==JZlib.Z_BUF_ERROR))
return(-1);
if(err!=JZlib.Z_OK && err!=JZlib.Z_STREAM_END)
throw new ZStreamException((compress ? "de" : "in")+"flating: "+z.msg);
if((nomoreinput||err==JZlib.Z_STREAM_END)&&(z.avail_out==len))
return(-1);
}
while(z.avail_out==len&&err==JZlib.Z_OK);
//System.err.print("("+(len-z.avail_out)+")");
return(len-z.avail_out);
}
public long skip(long n) throws IOException {
int len=512;
if(n<len)
len=(int)n;
byte[] tmp=new byte[len];
return((long)read(tmp));
}
public int getFlushMode() {
return(flush);
}
public void setFlushMode(int flush) {
this.flush=flush;
}
/**
* Returns the total number of bytes input so far.
*/
public long getTotalIn() {
return z.total_in;
}
/**
* Returns the total number of bytes output so far.
*/
public long getTotalOut() {
return z.total_out;
}
public void close() throws IOException{
in.close();
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/ZInputStream.java
|
Java
|
asf20
| 4,279
|
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2001 Lapo Luchini.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS
OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
import java.io.*;
public class ZOutputStream extends OutputStream {
protected ZStream z=new ZStream();
protected int bufsize=512;
protected int flush=JZlib.Z_NO_FLUSH;
protected byte[] buf=new byte[bufsize],
buf1=new byte[1];
protected boolean compress;
protected OutputStream out;
public ZOutputStream(OutputStream out) {
super();
this.out=out;
z.inflateInit();
compress=false;
}
public ZOutputStream(OutputStream out, int level) {
this(out, level, false);
}
public ZOutputStream(OutputStream out, int level, boolean nowrap) {
super();
this.out=out;
z.deflateInit(level, nowrap);
compress=true;
}
public void write(int b) throws IOException {
buf1[0]=(byte)b;
write(buf1, 0, 1);
}
public void write(byte b[], int off, int len) throws IOException {
if(len==0)
return;
int err;
z.next_in=b;
z.next_in_index=off;
z.avail_in=len;
do{
z.next_out=buf;
z.next_out_index=0;
z.avail_out=bufsize;
if(compress)
err=z.deflate(flush);
else
err=z.inflate(flush);
if(err!=JZlib.Z_OK)
throw new ZStreamException((compress?"de":"in")+"flating: "+z.msg);
out.write(buf, 0, bufsize-z.avail_out);
}
while(z.avail_in>0 || z.avail_out==0);
}
public int getFlushMode() {
return(flush);
}
public void setFlushMode(int flush) {
this.flush=flush;
}
public void finish() throws IOException {
int err;
do{
z.next_out=buf;
z.next_out_index=0;
z.avail_out=bufsize;
if(compress){ err=z.deflate(JZlib.Z_FINISH); }
else{ err=z.inflate(JZlib.Z_FINISH); }
if(err!=JZlib.Z_STREAM_END && err != JZlib.Z_OK)
throw new ZStreamException((compress?"de":"in")+"flating: "+z.msg);
if(bufsize-z.avail_out>0){
out.write(buf, 0, bufsize-z.avail_out);
}
}
while(z.avail_in>0 || z.avail_out==0);
flush();
}
public void end() {
if(z==null)
return;
if(compress){ z.deflateEnd(); }
else{ z.inflateEnd(); }
z.free();
z=null;
}
public void close() throws IOException {
try{
try{finish();}
catch (IOException ignored) {}
}
finally{
end();
out.close();
out=null;
}
}
/**
* Returns the total number of bytes input so far.
*/
public long getTotalIn() {
return z.total_in;
}
/**
* Returns the total number of bytes output so far.
*/
public long getTotalOut() {
return z.total_out;
}
public void flush() throws IOException {
out.flush();
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/ZOutputStream.java
|
Java
|
asf20
| 4,315
|
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class Inflate{
static final private int MAX_WBITS=15; // 32K LZ77 window
// preset dictionary flag in zlib header
static final private int PRESET_DICT=0x20;
static final int Z_NO_FLUSH=0;
static final int Z_PARTIAL_FLUSH=1;
static final int Z_SYNC_FLUSH=2;
static final int Z_FULL_FLUSH=3;
static final int Z_FINISH=4;
static final private int Z_DEFLATED=8;
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
static final private int METHOD=0; // waiting for method byte
static final private int FLAG=1; // waiting for flag byte
static final private int DICT4=2; // four dictionary check bytes to go
static final private int DICT3=3; // three dictionary check bytes to go
static final private int DICT2=4; // two dictionary check bytes to go
static final private int DICT1=5; // one dictionary check byte to go
static final private int DICT0=6; // waiting for inflateSetDictionary
static final private int BLOCKS=7; // decompressing blocks
static final private int CHECK4=8; // four check bytes to go
static final private int CHECK3=9; // three check bytes to go
static final private int CHECK2=10; // two check bytes to go
static final private int CHECK1=11; // one check byte to go
static final private int DONE=12; // finished check, done
static final private int BAD=13; // got an error--stay here
int mode; // current inflate mode
// mode dependent information
int method; // if FLAGS, method byte
// if CHECK, check values to compare
long[] was=new long[1] ; // computed check value
long need; // stream check value
// if BAD, inflateSync's marker bytes count
int marker;
// mode independent information
int nowrap; // flag for no wrapper
int wbits; // log2(window size) (8..15, defaults to 15)
InfBlocks blocks; // current inflate_blocks state
int inflateReset(ZStream z){
if(z == null || z.istate == null) return Z_STREAM_ERROR;
z.total_in = z.total_out = 0;
z.msg = null;
z.istate.mode = z.istate.nowrap!=0 ? BLOCKS : METHOD;
z.istate.blocks.reset(z, null);
return Z_OK;
}
int inflateEnd(ZStream z){
if(blocks != null)
blocks.free(z);
blocks=null;
// ZFREE(z, z->state);
return Z_OK;
}
int inflateInit(ZStream z, int w){
z.msg = null;
blocks = null;
// handle undocumented nowrap option (no zlib header or check)
nowrap = 0;
if(w < 0){
w = - w;
nowrap = 1;
}
// set window size
if(w<8 ||w>15){
inflateEnd(z);
return Z_STREAM_ERROR;
}
wbits=w;
z.istate.blocks=new InfBlocks(z,
z.istate.nowrap!=0 ? null : this,
1<<w);
// reset state
inflateReset(z);
return Z_OK;
}
int inflate(ZStream z, int f){
int r;
int b;
if(z == null || z.istate == null || z.next_in == null)
return Z_STREAM_ERROR;
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
while (true){
//System.out.println("mode: "+z.istate.mode);
switch (z.istate.mode){
case METHOD:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
if(((z.istate.method = z.next_in[z.next_in_index++])&0xf)!=Z_DEFLATED){
z.istate.mode = BAD;
z.msg="unknown compression method";
z.istate.marker = 5; // can't try inflateSync
break;
}
if((z.istate.method>>4)+8>z.istate.wbits){
z.istate.mode = BAD;
z.msg="invalid window size";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode=FLAG;
case FLAG:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
b = (z.next_in[z.next_in_index++])&0xff;
if((((z.istate.method << 8)+b) % 31)!=0){
z.istate.mode = BAD;
z.msg = "incorrect header check";
z.istate.marker = 5; // can't try inflateSync
break;
}
if((b&PRESET_DICT)==0){
z.istate.mode = BLOCKS;
break;
}
z.istate.mode = DICT4;
case DICT4:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
z.istate.mode=DICT3;
case DICT3:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
z.istate.mode=DICT2;
case DICT2:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
z.istate.mode=DICT1;
case DICT1:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need += (z.next_in[z.next_in_index++]&0xffL);
z.adler = z.istate.need;
z.istate.mode = DICT0;
return Z_NEED_DICT;
case DICT0:
z.istate.mode = BAD;
z.msg = "need dictionary";
z.istate.marker = 0; // can try inflateSync
return Z_STREAM_ERROR;
case BLOCKS:
r = z.istate.blocks.proc(z, r);
if(r == Z_DATA_ERROR){
z.istate.mode = BAD;
z.istate.marker = 0; // can try inflateSync
break;
}
if(r == Z_OK){
r = f;
}
if(r != Z_STREAM_END){
return r;
}
r = f;
z.istate.blocks.reset(z, z.istate.was);
if(z.istate.nowrap!=0){
z.istate.mode=DONE;
break;
}
z.istate.mode=CHECK4;
case CHECK4:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
z.istate.mode=CHECK3;
case CHECK3:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
z.istate.mode = CHECK2;
case CHECK2:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
z.istate.mode = CHECK1;
case CHECK1:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=(z.next_in[z.next_in_index++]&0xffL);
if(((int)(z.istate.was[0])) != ((int)(z.istate.need))){
z.istate.mode = BAD;
z.msg = "incorrect data check";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode = DONE;
case DONE:
return Z_STREAM_END;
case BAD:
return Z_DATA_ERROR;
default:
return Z_STREAM_ERROR;
}
}
}
int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength){
int index=0;
int length = dictLength;
if(z==null || z.istate == null|| z.istate.mode != DICT0)
return Z_STREAM_ERROR;
if(z._adler.adler32(1L, dictionary, 0, dictLength)!=z.adler){
return Z_DATA_ERROR;
}
z.adler = z._adler.adler32(0, null, 0, 0);
if(length >= (1<<z.istate.wbits)){
length = (1<<z.istate.wbits)-1;
index=dictLength - length;
}
z.istate.blocks.set_dictionary(dictionary, index, length);
z.istate.mode = BLOCKS;
return Z_OK;
}
static private byte[] mark = {(byte)0, (byte)0, (byte)0xff, (byte)0xff};
int inflateSync(ZStream z){
int n; // number of bytes to look at
int p; // pointer to bytes
int m; // number of marker bytes found in a row
long r, w; // temporaries to save total_in and total_out
// set up
if(z == null || z.istate == null)
return Z_STREAM_ERROR;
if(z.istate.mode != BAD){
z.istate.mode = BAD;
z.istate.marker = 0;
}
if((n=z.avail_in)==0)
return Z_BUF_ERROR;
p=z.next_in_index;
m=z.istate.marker;
// search
while (n!=0 && m < 4){
if(z.next_in[p] == mark[m]){
m++;
}
else if(z.next_in[p]!=0){
m = 0;
}
else{
m = 4 - m;
}
p++; n--;
}
// restore
z.total_in += p-z.next_in_index;
z.next_in_index = p;
z.avail_in = n;
z.istate.marker = m;
// return no joy or set up to restart on a new block
if(m != 4){
return Z_DATA_ERROR;
}
r=z.total_in; w=z.total_out;
inflateReset(z);
z.total_in=r; z.total_out = w;
z.istate.mode = BLOCKS;
return Z_OK;
}
// Returns true if inflate is currently at the end of a block generated
// by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
// implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
// but removes the length bytes of the resulting empty stored block. When
// decompressing, PPP checks that at the end of input packet, inflate is
// waiting for these length bytes.
int inflateSyncPoint(ZStream z){
if(z == null || z.istate == null || z.istate.blocks == null)
return Z_STREAM_ERROR;
return z.istate.blocks.sync_point();
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/Inflate.java
|
Java
|
asf20
| 11,302
|
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class InfCodes{
static final private int[] inflate_mask = {
0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff,
0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff,
0x00007fff, 0x0000ffff
};
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
// waiting for "i:"=input,
// "o:"=output,
// "x:"=nothing
static final private int START=0; // x: set up for LEN
static final private int LEN=1; // i: get length/literal/eob next
static final private int LENEXT=2; // i: getting length extra (have base)
static final private int DIST=3; // i: get distance next
static final private int DISTEXT=4;// i: getting distance extra
static final private int COPY=5; // o: copying bytes in window, waiting for space
static final private int LIT=6; // o: got literal, waiting for output space
static final private int WASH=7; // o: got eob, possibly still output waiting
static final private int END=8; // x: got eob and all data flushed
static final private int BADCODE=9;// x: got error
int mode; // current inflate_codes mode
// mode dependent information
int len;
int[] tree; // pointer into tree
int tree_index=0;
int need; // bits needed
int lit;
// if EXT or COPY, where and how much
int get; // bits to get for extra
int dist; // distance back to copy from
byte lbits; // ltree bits decoded per branch
byte dbits; // dtree bits decoder per branch
int[] ltree; // literal/length/eob tree
int ltree_index; // literal/length/eob tree
int[] dtree; // distance tree
int dtree_index; // distance tree
InfCodes(){
}
void init(int bl, int bd,
int[] tl, int tl_index,
int[] td, int td_index, ZStream z){
mode=START;
lbits=(byte)bl;
dbits=(byte)bd;
ltree=tl;
ltree_index=tl_index;
dtree = td;
dtree_index=td_index;
tree=null;
}
int proc(InfBlocks s, ZStream z, int r){
int j; // temporary storage
int[] t; // temporary pointer
int tindex; // temporary pointer
int e; // extra bits or operation
int b=0; // bit buffer
int k=0; // bits in bit buffer
int p=0; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
int f; // pointer to copy strings from
// copy input/output information to locals (UPDATE macro restores)
p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
// process input and output based on current state
while (true){
switch (mode){
// waiting for "i:"=input, "o:"=output, "x:"=nothing
case START: // x: set up for LEN
if (m >= 258 && n >= 10){
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
r = inflate_fast(lbits, dbits,
ltree, ltree_index,
dtree, dtree_index,
s, z);
p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
if (r != Z_OK){
mode = r == Z_STREAM_END ? WASH : BADCODE;
break;
}
}
need = lbits;
tree = ltree;
tree_index=ltree_index;
mode = LEN;
case LEN: // i: get length/literal/eob next
j = need;
while(k<(j)){
if(n!=0)r=Z_OK;
else{
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
}
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
tindex=(tree_index+(b&inflate_mask[j]))*3;
b>>>=(tree[tindex+1]);
k-=(tree[tindex+1]);
e=tree[tindex];
if(e == 0){ // literal
lit = tree[tindex+2];
mode = LIT;
break;
}
if((e & 16)!=0 ){ // length
get = e & 15;
len = tree[tindex+2];
mode = LENEXT;
break;
}
if ((e & 64) == 0){ // next table
need = e;
tree_index = tindex/3+tree[tindex+2];
break;
}
if ((e & 32)!=0){ // end of block
mode = WASH;
break;
}
mode = BADCODE; // invalid code
z.msg = "invalid literal/length code";
r = Z_DATA_ERROR;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
case LENEXT: // i: getting length extra (have base)
j = get;
while(k<(j)){
if(n!=0)r=Z_OK;
else{
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
}
n--; b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
len += (b & inflate_mask[j]);
b>>=j;
k-=j;
need = dbits;
tree = dtree;
tree_index=dtree_index;
mode = DIST;
case DIST: // i: get distance next
j = need;
while(k<(j)){
if(n!=0)r=Z_OK;
else{
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
}
n--; b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
tindex=(tree_index+(b & inflate_mask[j]))*3;
b>>=tree[tindex+1];
k-=tree[tindex+1];
e = (tree[tindex]);
if((e & 16)!=0){ // distance
get = e & 15;
dist = tree[tindex+2];
mode = DISTEXT;
break;
}
if ((e & 64) == 0){ // next table
need = e;
tree_index = tindex/3 + tree[tindex+2];
break;
}
mode = BADCODE; // invalid code
z.msg = "invalid distance code";
r = Z_DATA_ERROR;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
case DISTEXT: // i: getting distance extra
j = get;
while(k<(j)){
if(n!=0)r=Z_OK;
else{
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
}
n--; b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
dist += (b & inflate_mask[j]);
b>>=j;
k-=j;
mode = COPY;
case COPY: // o: copying bytes in window, waiting for space
f = q - dist;
while(f < 0){ // modulo window size-"while" instead
f += s.end; // of "if" handles invalid distances
}
while (len!=0){
if(m==0){
if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;}
if(m==0){
s.write=q; r=s.inflate_flush(z,r);
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;}
if(m==0){
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
}
}
}
s.window[q++]=s.window[f++]; m--;
if (f == s.end)
f = 0;
len--;
}
mode = START;
break;
case LIT: // o: got literal, waiting for output space
if(m==0){
if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;}
if(m==0){
s.write=q; r=s.inflate_flush(z,r);
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;}
if(m==0){
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
}
}
}
r=Z_OK;
s.window[q++]=(byte)lit; m--;
mode = START;
break;
case WASH: // o: got eob, possibly more output
if (k > 7){ // return unused byte, if any
k -= 8;
n++;
p--; // can always return one
}
s.write=q; r=s.inflate_flush(z,r);
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
if (s.read != s.write){
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
}
mode = END;
case END:
r = Z_STREAM_END;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
case BADCODE: // x: got error
r = Z_DATA_ERROR;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
default:
r = Z_STREAM_ERROR;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(z,r);
}
}
}
void free(ZStream z){
// ZFREE(z, c);
}
// Called with number of bytes left to write in window at least 258
// (the maximum string length) and number of input bytes available
// at least ten. The ten bytes are six bytes for the longest length/
// distance pair plus four bytes for overloading the bit buffer.
int inflate_fast(int bl, int bd,
int[] tl, int tl_index,
int[] td, int td_index,
InfBlocks s, ZStream z){
int t; // temporary pointer
int[] tp; // temporary pointer
int tp_index; // temporary pointer
int e; // extra bits or operation
int b; // bit buffer
int k; // bits in bit buffer
int p; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
int ml; // mask for literal/length tree
int md; // mask for distance tree
int c; // bytes to copy
int d; // distance back to copy from
int r; // copy source pointer
int tp_index_t_3; // (tp_index+t)*3
// load input, output, bit values
p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
// initialize masks
ml = inflate_mask[bl];
md = inflate_mask[bd];
// do until not enough input or output space for fast loop
do { // assume called with m >= 258 && n >= 10
// get literal/length code
while(k<(20)){ // max bits for literal/length code
n--;
b|=(z.next_in[p++]&0xff)<<k;k+=8;
}
t= b&ml;
tp=tl;
tp_index=tl_index;
tp_index_t_3=(tp_index+t)*3;
if ((e = tp[tp_index_t_3]) == 0){
b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
s.window[q++] = (byte)tp[tp_index_t_3+2];
m--;
continue;
}
do {
b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
if((e&16)!=0){
e &= 15;
c = tp[tp_index_t_3+2] + ((int)b & inflate_mask[e]);
b>>=e; k-=e;
// decode distance base of block to copy
while(k<(15)){ // max bits for distance code
n--;
b|=(z.next_in[p++]&0xff)<<k;k+=8;
}
t= b&md;
tp=td;
tp_index=td_index;
tp_index_t_3=(tp_index+t)*3;
e = tp[tp_index_t_3];
do {
b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
if((e&16)!=0){
// get extra bits to add to distance base
e &= 15;
while(k<(e)){ // get extra bits (up to 13)
n--;
b|=(z.next_in[p++]&0xff)<<k;k+=8;
}
d = tp[tp_index_t_3+2] + (b&inflate_mask[e]);
b>>=(e); k-=(e);
// do the copy
m -= c;
if (q >= d){ // offset before dest
// just copy
r=q-d;
if(q-r>0 && 2>(q-r)){
s.window[q++]=s.window[r++]; // minimum count is three,
s.window[q++]=s.window[r++]; // so unroll loop a little
c-=2;
}
else{
System.arraycopy(s.window, r, s.window, q, 2);
q+=2; r+=2; c-=2;
}
}
else{ // else offset after destination
r=q-d;
do{
r+=s.end; // force pointer in window
}while(r<0); // covers invalid distances
e=s.end-r;
if(c>e){ // if source crosses,
c-=e; // wrapped copy
if(q-r>0 && e>(q-r)){
do{s.window[q++] = s.window[r++];}
while(--e!=0);
}
else{
System.arraycopy(s.window, r, s.window, q, e);
q+=e; r+=e; e=0;
}
r = 0; // copy rest from start of window
}
}
// copy all or what's left
if(q-r>0 && c>(q-r)){
do{s.window[q++] = s.window[r++];}
while(--c!=0);
}
else{
System.arraycopy(s.window, r, s.window, q, c);
q+=c; r+=c; c=0;
}
break;
}
else if((e&64)==0){
t+=tp[tp_index_t_3+2];
t+=(b&inflate_mask[e]);
tp_index_t_3=(tp_index+t)*3;
e=tp[tp_index_t_3];
}
else{
z.msg = "invalid distance code";
c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return Z_DATA_ERROR;
}
}
while(true);
break;
}
if((e&64)==0){
t+=tp[tp_index_t_3+2];
t+=(b&inflate_mask[e]);
tp_index_t_3=(tp_index+t)*3;
if((e=tp[tp_index_t_3])==0){
b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
s.window[q++]=(byte)tp[tp_index_t_3+2];
m--;
break;
}
}
else if((e&32)!=0){
c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return Z_STREAM_END;
}
else{
z.msg="invalid literal/length code";
c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return Z_DATA_ERROR;
}
}
while(true);
}
while(m>=258 && n>= 10);
// not enough input or output--restore pointers and return
c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return Z_OK;
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/InfCodes.java
|
Java
|
asf20
| 16,042
|
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final public class ZStream{
static final private int MAX_WBITS=15; // 32K LZ77 window
static final private int DEF_WBITS=MAX_WBITS;
static final private int Z_NO_FLUSH=0;
static final private int Z_PARTIAL_FLUSH=1;
static final private int Z_SYNC_FLUSH=2;
static final private int Z_FULL_FLUSH=3;
static final private int Z_FINISH=4;
static final private int MAX_MEM_LEVEL=9;
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
public byte[] next_in; // next input byte
public int next_in_index;
public int avail_in; // number of bytes available at next_in
public long total_in; // total nb of input bytes read so far
public byte[] next_out; // next output byte should be put there
public int next_out_index;
public int avail_out; // remaining free space at next_out
public long total_out; // total nb of bytes output so far
public String msg;
Deflate dstate;
Inflate istate;
int data_type; // best guess about the data type: ascii or binary
public long adler;
Adler32 _adler=new Adler32();
public int inflateInit(){
return inflateInit(DEF_WBITS);
}
public int inflateInit(boolean nowrap){
return inflateInit(DEF_WBITS, nowrap);
}
public int inflateInit(int w){
return inflateInit(w, false);
}
public int inflateInit(int w, boolean nowrap){
istate=new Inflate();
return istate.inflateInit(this, nowrap?-w:w);
}
public int inflate(int f){
if(istate==null) return Z_STREAM_ERROR;
return istate.inflate(this, f);
}
public int inflateEnd(){
if(istate==null) return Z_STREAM_ERROR;
int ret=istate.inflateEnd(this);
istate = null;
return ret;
}
public int inflateSync(){
if(istate == null)
return Z_STREAM_ERROR;
return istate.inflateSync(this);
}
public int inflateSetDictionary(byte[] dictionary, int dictLength){
if(istate == null)
return Z_STREAM_ERROR;
return istate.inflateSetDictionary(this, dictionary, dictLength);
}
public int deflateInit(int level){
return deflateInit(level, MAX_WBITS);
}
public int deflateInit(int level, boolean nowrap){
return deflateInit(level, MAX_WBITS, nowrap);
}
public int deflateInit(int level, int bits){
return deflateInit(level, bits, false);
}
public int deflateInit(int level, int bits, boolean nowrap){
dstate=new Deflate();
return dstate.deflateInit(this, level, nowrap?-bits:bits);
}
public int deflate(int flush){
if(dstate==null){
return Z_STREAM_ERROR;
}
return dstate.deflate(this, flush);
}
public int deflateEnd(){
if(dstate==null) return Z_STREAM_ERROR;
int ret=dstate.deflateEnd();
dstate=null;
return ret;
}
public int deflateParams(int level, int strategy){
if(dstate==null) return Z_STREAM_ERROR;
return dstate.deflateParams(this, level, strategy);
}
public int deflateSetDictionary (byte[] dictionary, int dictLength){
if(dstate == null)
return Z_STREAM_ERROR;
return dstate.deflateSetDictionary(this, dictionary, dictLength);
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
void flush_pending(){
int len=dstate.pending;
if(len>avail_out) len=avail_out;
if(len==0) return;
if(dstate.pending_buf.length<=dstate.pending_out ||
next_out.length<=next_out_index ||
dstate.pending_buf.length<(dstate.pending_out+len) ||
next_out.length<(next_out_index+len)){
System.out.println(dstate.pending_buf.length+", "+dstate.pending_out+
", "+next_out.length+", "+next_out_index+", "+len);
System.out.println("avail_out="+avail_out);
}
System.arraycopy(dstate.pending_buf, dstate.pending_out,
next_out, next_out_index, len);
next_out_index+=len;
dstate.pending_out+=len;
total_out+=len;
avail_out-=len;
dstate.pending-=len;
if(dstate.pending==0){
dstate.pending_out=0;
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
int read_buf(byte[] buf, int start, int size) {
int len=avail_in;
if(len>size) len=size;
if(len==0) return 0;
avail_in-=len;
if(dstate.noheader==0) {
adler=_adler.adler32(adler, next_in, next_in_index, len);
}
System.arraycopy(next_in, next_in_index, buf, start, len);
next_in_index += len;
total_in += len;
return len;
}
public void free(){
next_in=null;
next_out=null;
msg=null;
_adler=null;
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/ZStream.java
|
Java
|
asf20
| 6,990
|
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class InfTree{
static final private int MANY=1440;
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
static final int fixed_bl = 9;
static final int fixed_bd = 5;
static final int[] fixed_tl = {
96,7,256, 0,8,80, 0,8,16, 84,8,115,
82,7,31, 0,8,112, 0,8,48, 0,9,192,
80,7,10, 0,8,96, 0,8,32, 0,9,160,
0,8,0, 0,8,128, 0,8,64, 0,9,224,
80,7,6, 0,8,88, 0,8,24, 0,9,144,
83,7,59, 0,8,120, 0,8,56, 0,9,208,
81,7,17, 0,8,104, 0,8,40, 0,9,176,
0,8,8, 0,8,136, 0,8,72, 0,9,240,
80,7,4, 0,8,84, 0,8,20, 85,8,227,
83,7,43, 0,8,116, 0,8,52, 0,9,200,
81,7,13, 0,8,100, 0,8,36, 0,9,168,
0,8,4, 0,8,132, 0,8,68, 0,9,232,
80,7,8, 0,8,92, 0,8,28, 0,9,152,
84,7,83, 0,8,124, 0,8,60, 0,9,216,
82,7,23, 0,8,108, 0,8,44, 0,9,184,
0,8,12, 0,8,140, 0,8,76, 0,9,248,
80,7,3, 0,8,82, 0,8,18, 85,8,163,
83,7,35, 0,8,114, 0,8,50, 0,9,196,
81,7,11, 0,8,98, 0,8,34, 0,9,164,
0,8,2, 0,8,130, 0,8,66, 0,9,228,
80,7,7, 0,8,90, 0,8,26, 0,9,148,
84,7,67, 0,8,122, 0,8,58, 0,9,212,
82,7,19, 0,8,106, 0,8,42, 0,9,180,
0,8,10, 0,8,138, 0,8,74, 0,9,244,
80,7,5, 0,8,86, 0,8,22, 192,8,0,
83,7,51, 0,8,118, 0,8,54, 0,9,204,
81,7,15, 0,8,102, 0,8,38, 0,9,172,
0,8,6, 0,8,134, 0,8,70, 0,9,236,
80,7,9, 0,8,94, 0,8,30, 0,9,156,
84,7,99, 0,8,126, 0,8,62, 0,9,220,
82,7,27, 0,8,110, 0,8,46, 0,9,188,
0,8,14, 0,8,142, 0,8,78, 0,9,252,
96,7,256, 0,8,81, 0,8,17, 85,8,131,
82,7,31, 0,8,113, 0,8,49, 0,9,194,
80,7,10, 0,8,97, 0,8,33, 0,9,162,
0,8,1, 0,8,129, 0,8,65, 0,9,226,
80,7,6, 0,8,89, 0,8,25, 0,9,146,
83,7,59, 0,8,121, 0,8,57, 0,9,210,
81,7,17, 0,8,105, 0,8,41, 0,9,178,
0,8,9, 0,8,137, 0,8,73, 0,9,242,
80,7,4, 0,8,85, 0,8,21, 80,8,258,
83,7,43, 0,8,117, 0,8,53, 0,9,202,
81,7,13, 0,8,101, 0,8,37, 0,9,170,
0,8,5, 0,8,133, 0,8,69, 0,9,234,
80,7,8, 0,8,93, 0,8,29, 0,9,154,
84,7,83, 0,8,125, 0,8,61, 0,9,218,
82,7,23, 0,8,109, 0,8,45, 0,9,186,
0,8,13, 0,8,141, 0,8,77, 0,9,250,
80,7,3, 0,8,83, 0,8,19, 85,8,195,
83,7,35, 0,8,115, 0,8,51, 0,9,198,
81,7,11, 0,8,99, 0,8,35, 0,9,166,
0,8,3, 0,8,131, 0,8,67, 0,9,230,
80,7,7, 0,8,91, 0,8,27, 0,9,150,
84,7,67, 0,8,123, 0,8,59, 0,9,214,
82,7,19, 0,8,107, 0,8,43, 0,9,182,
0,8,11, 0,8,139, 0,8,75, 0,9,246,
80,7,5, 0,8,87, 0,8,23, 192,8,0,
83,7,51, 0,8,119, 0,8,55, 0,9,206,
81,7,15, 0,8,103, 0,8,39, 0,9,174,
0,8,7, 0,8,135, 0,8,71, 0,9,238,
80,7,9, 0,8,95, 0,8,31, 0,9,158,
84,7,99, 0,8,127, 0,8,63, 0,9,222,
82,7,27, 0,8,111, 0,8,47, 0,9,190,
0,8,15, 0,8,143, 0,8,79, 0,9,254,
96,7,256, 0,8,80, 0,8,16, 84,8,115,
82,7,31, 0,8,112, 0,8,48, 0,9,193,
80,7,10, 0,8,96, 0,8,32, 0,9,161,
0,8,0, 0,8,128, 0,8,64, 0,9,225,
80,7,6, 0,8,88, 0,8,24, 0,9,145,
83,7,59, 0,8,120, 0,8,56, 0,9,209,
81,7,17, 0,8,104, 0,8,40, 0,9,177,
0,8,8, 0,8,136, 0,8,72, 0,9,241,
80,7,4, 0,8,84, 0,8,20, 85,8,227,
83,7,43, 0,8,116, 0,8,52, 0,9,201,
81,7,13, 0,8,100, 0,8,36, 0,9,169,
0,8,4, 0,8,132, 0,8,68, 0,9,233,
80,7,8, 0,8,92, 0,8,28, 0,9,153,
84,7,83, 0,8,124, 0,8,60, 0,9,217,
82,7,23, 0,8,108, 0,8,44, 0,9,185,
0,8,12, 0,8,140, 0,8,76, 0,9,249,
80,7,3, 0,8,82, 0,8,18, 85,8,163,
83,7,35, 0,8,114, 0,8,50, 0,9,197,
81,7,11, 0,8,98, 0,8,34, 0,9,165,
0,8,2, 0,8,130, 0,8,66, 0,9,229,
80,7,7, 0,8,90, 0,8,26, 0,9,149,
84,7,67, 0,8,122, 0,8,58, 0,9,213,
82,7,19, 0,8,106, 0,8,42, 0,9,181,
0,8,10, 0,8,138, 0,8,74, 0,9,245,
80,7,5, 0,8,86, 0,8,22, 192,8,0,
83,7,51, 0,8,118, 0,8,54, 0,9,205,
81,7,15, 0,8,102, 0,8,38, 0,9,173,
0,8,6, 0,8,134, 0,8,70, 0,9,237,
80,7,9, 0,8,94, 0,8,30, 0,9,157,
84,7,99, 0,8,126, 0,8,62, 0,9,221,
82,7,27, 0,8,110, 0,8,46, 0,9,189,
0,8,14, 0,8,142, 0,8,78, 0,9,253,
96,7,256, 0,8,81, 0,8,17, 85,8,131,
82,7,31, 0,8,113, 0,8,49, 0,9,195,
80,7,10, 0,8,97, 0,8,33, 0,9,163,
0,8,1, 0,8,129, 0,8,65, 0,9,227,
80,7,6, 0,8,89, 0,8,25, 0,9,147,
83,7,59, 0,8,121, 0,8,57, 0,9,211,
81,7,17, 0,8,105, 0,8,41, 0,9,179,
0,8,9, 0,8,137, 0,8,73, 0,9,243,
80,7,4, 0,8,85, 0,8,21, 80,8,258,
83,7,43, 0,8,117, 0,8,53, 0,9,203,
81,7,13, 0,8,101, 0,8,37, 0,9,171,
0,8,5, 0,8,133, 0,8,69, 0,9,235,
80,7,8, 0,8,93, 0,8,29, 0,9,155,
84,7,83, 0,8,125, 0,8,61, 0,9,219,
82,7,23, 0,8,109, 0,8,45, 0,9,187,
0,8,13, 0,8,141, 0,8,77, 0,9,251,
80,7,3, 0,8,83, 0,8,19, 85,8,195,
83,7,35, 0,8,115, 0,8,51, 0,9,199,
81,7,11, 0,8,99, 0,8,35, 0,9,167,
0,8,3, 0,8,131, 0,8,67, 0,9,231,
80,7,7, 0,8,91, 0,8,27, 0,9,151,
84,7,67, 0,8,123, 0,8,59, 0,9,215,
82,7,19, 0,8,107, 0,8,43, 0,9,183,
0,8,11, 0,8,139, 0,8,75, 0,9,247,
80,7,5, 0,8,87, 0,8,23, 192,8,0,
83,7,51, 0,8,119, 0,8,55, 0,9,207,
81,7,15, 0,8,103, 0,8,39, 0,9,175,
0,8,7, 0,8,135, 0,8,71, 0,9,239,
80,7,9, 0,8,95, 0,8,31, 0,9,159,
84,7,99, 0,8,127, 0,8,63, 0,9,223,
82,7,27, 0,8,111, 0,8,47, 0,9,191,
0,8,15, 0,8,143, 0,8,79, 0,9,255
};
static final int[] fixed_td = {
80,5,1, 87,5,257, 83,5,17, 91,5,4097,
81,5,5, 89,5,1025, 85,5,65, 93,5,16385,
80,5,3, 88,5,513, 84,5,33, 92,5,8193,
82,5,9, 90,5,2049, 86,5,129, 192,5,24577,
80,5,2, 87,5,385, 83,5,25, 91,5,6145,
81,5,7, 89,5,1537, 85,5,97, 93,5,24577,
80,5,4, 88,5,769, 84,5,49, 92,5,12289,
82,5,13, 90,5,3073, 86,5,193, 192,5,24577
};
// Tables for deflate from PKZIP's appnote.txt.
static final int[] cplens = { // Copy lengths for literal codes 257..285
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
};
// see note #13 above about 258
static final int[] cplext = { // Extra bits for literal codes 257..285
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid
};
static final int[] cpdist = { // Copy offsets for distance codes 0..29
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577
};
static final int[] cpdext = { // Extra bits for distance codes
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13};
// If BMAX needs to be larger than 16, then h and x[] should be uLong.
static final int BMAX=15; // maximum bit length of any code
int[] hn = null; // hufts used in space
int[] v = null; // work area for huft_build
int[] c = null; // bit length count table
int[] r = null; // table entry for structure assignment
int[] u = null; // table stack
int[] x = null; // bit offsets, then code stack
private int huft_build(int[] b, // code lengths in bits (all assumed <= BMAX)
int bindex,
int n, // number of codes (assumed <= 288)
int s, // number of simple-valued codes (0..s-1)
int[] d, // list of base values for non-simple codes
int[] e, // list of extra bits for non-simple codes
int[] t, // result: starting table
int[] m, // maximum lookup bits, returns actual
int[] hp,// space for trees
int[] hn,// hufts used in space
int[] v // working area: values in order of bit length
){
// Given a list of code lengths and a maximum table size, make a set of
// tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
// if the given code set is incomplete (the tables are still built in this
// case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
// lengths), or Z_MEM_ERROR if not enough memory.
int a; // counter for codes of length k
int f; // i repeats in table every f entries
int g; // maximum code length
int h; // table level
int i; // counter, current code
int j; // counter
int k; // number of bits in current code
int l; // bits per table (returned in m)
int mask; // (1 << w) - 1, to avoid cc -O bug on HP
int p; // pointer into c[], b[], or v[]
int q; // points to current table
int w; // bits before this table == (l * h)
int xp; // pointer into x
int y; // number of dummy codes added
int z; // number of entries in current table
// Generate counts for each bit length
p = 0; i = n;
do {
c[b[bindex+p]]++; p++; i--; // assume all entries <= BMAX
}while(i!=0);
if(c[0] == n){ // null input--all zero length codes
t[0] = -1;
m[0] = 0;
return Z_OK;
}
// Find minimum and maximum length, bound *m by those
l = m[0];
for (j = 1; j <= BMAX; j++)
if(c[j]!=0) break;
k = j; // minimum code length
if(l < j){
l = j;
}
for (i = BMAX; i!=0; i--){
if(c[i]!=0) break;
}
g = i; // maximum code length
if(l > i){
l = i;
}
m[0] = l;
// Adjust last length count to fill out codes, if needed
for (y = 1 << j; j < i; j++, y <<= 1){
if ((y -= c[j]) < 0){
return Z_DATA_ERROR;
}
}
if ((y -= c[i]) < 0){
return Z_DATA_ERROR;
}
c[i] += y;
// Generate starting offsets into the value table for each length
x[1] = j = 0;
p = 1; xp = 2;
while (--i!=0) { // note that i == g from above
x[xp] = (j += c[p]);
xp++;
p++;
}
// Make a table of values in order of bit lengths
i = 0; p = 0;
do {
if ((j = b[bindex+p]) != 0){
v[x[j]++] = i;
}
p++;
}
while (++i < n);
n = x[g]; // set n to length of v
// Generate the Huffman codes and for each, make the table entries
x[0] = i = 0; // first Huffman code is zero
p = 0; // grab values in bit order
h = -1; // no tables yet--level -1
w = -l; // bits decoded == (l * h)
u[0] = 0; // just to keep compilers happy
q = 0; // ditto
z = 0; // ditto
// go through the bit lengths (k already is bits in shortest code)
for (; k <= g; k++){
a = c[k];
while (a--!=0){
// here i is the Huffman code of length k bits for value *p
// make tables up to required level
while (k > w + l){
h++;
w += l; // previous table always l bits
// compute minimum size table less than or equal to l bits
z = g - w;
z = (z > l) ? l : z; // table size upper limit
if((f=1<<(j=k-w))>a+1){ // try a k-w bit table
// too few codes for k-w bit table
f -= a + 1; // deduct codes from patterns left
xp = k;
if(j < z){
while (++j < z){ // try smaller tables up to z bits
if((f <<= 1) <= c[++xp])
break; // enough codes to use up j bits
f -= c[xp]; // else deduct codes from patterns
}
}
}
z = 1 << j; // table entries for j-bit table
// allocate new table
if (hn[0] + z > MANY){ // (note: doesn't matter for fixed)
return Z_DATA_ERROR; // overflow of MANY
}
u[h] = q = /*hp+*/ hn[0]; // DEBUG
hn[0] += z;
// connect to last table, if there is one
if(h!=0){
x[h]=i; // save pattern for backing up
r[0]=(byte)j; // bits in this table
r[1]=(byte)l; // bits to dump before this table
j=i>>>(w - l);
r[2] = (int)(q - u[h-1] - j); // offset to this table
System.arraycopy(r, 0, hp, (u[h-1]+j)*3, 3); // connect to last table
}
else{
t[0] = q; // first table is returned result
}
}
// set up table entry in r
r[1] = (byte)(k - w);
if (p >= n){
r[0] = 128 + 64; // out of values--invalid code
}
else if (v[p] < s){
r[0] = (byte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block
r[2] = v[p++]; // simple code is just the value
}
else{
r[0]=(byte)(e[v[p]-s]+16+64); // non-simple--look up in lists
r[2]=d[v[p++] - s];
}
// fill code-like entries with r
f=1<<(k-w);
for (j=i>>>w;j<z;j+=f){
System.arraycopy(r, 0, hp, (q+j)*3, 3);
}
// backwards increment the k-bit code i
for (j = 1 << (k - 1); (i & j)!=0; j >>>= 1){
i ^= j;
}
i ^= j;
// backup over finished tables
mask = (1 << w) - 1; // needed on HP, cc -O bug
while ((i & mask) != x[h]){
h--; // don't need to update q
w -= l;
mask = (1 << w) - 1;
}
}
}
// Return Z_BUF_ERROR if we were given an incomplete table
return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
}
int inflate_trees_bits(int[] c, // 19 code lengths
int[] bb, // bits tree desired/actual depth
int[] tb, // bits tree result
int[] hp, // space for trees
ZStream z // for messages
){
int result;
initWorkArea(19);
hn[0]=0;
result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
if(result == Z_DATA_ERROR){
z.msg = "oversubscribed dynamic bit lengths tree";
}
else if(result == Z_BUF_ERROR || bb[0] == 0){
z.msg = "incomplete dynamic bit lengths tree";
result = Z_DATA_ERROR;
}
return result;
}
int inflate_trees_dynamic(int nl, // number of literal/length codes
int nd, // number of distance codes
int[] c, // that many (total) code lengths
int[] bl, // literal desired/actual bit depth
int[] bd, // distance desired/actual bit depth
int[] tl, // literal/length tree result
int[] td, // distance tree result
int[] hp, // space for trees
ZStream z // for messages
){
int result;
// build literal/length tree
initWorkArea(288);
hn[0]=0;
result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v);
if (result != Z_OK || bl[0] == 0){
if(result == Z_DATA_ERROR){
z.msg = "oversubscribed literal/length tree";
}
else if (result != Z_MEM_ERROR){
z.msg = "incomplete literal/length tree";
result = Z_DATA_ERROR;
}
return result;
}
// build distance tree
initWorkArea(288);
result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v);
if (result != Z_OK || (bd[0] == 0 && nl > 257)){
if (result == Z_DATA_ERROR){
z.msg = "oversubscribed distance tree";
}
else if (result == Z_BUF_ERROR) {
z.msg = "incomplete distance tree";
result = Z_DATA_ERROR;
}
else if (result != Z_MEM_ERROR){
z.msg = "empty distance tree with lengths";
result = Z_DATA_ERROR;
}
return result;
}
return Z_OK;
}
static int inflate_trees_fixed(int[] bl, //literal desired/actual bit depth
int[] bd, //distance desired/actual bit depth
int[][] tl,//literal/length tree result
int[][] td,//distance tree result
ZStream z //for memory allocation
){
bl[0]=fixed_bl;
bd[0]=fixed_bd;
tl[0]=fixed_tl;
td[0]=fixed_td;
return Z_OK;
}
private void initWorkArea(int vsize){
if(hn==null){
hn=new int[1];
v=new int[vsize];
c=new int[BMAX+1];
r=new int[3];
u=new int[BMAX];
x=new int[BMAX+1];
}
if(v.length<vsize){ v=new int[vsize]; }
for(int i=0; i<vsize; i++){v[i]=0;}
for(int i=0; i<BMAX+1; i++){c[i]=0;}
for(int i=0; i<3; i++){r[i]=0;}
// for(int i=0; i<BMAX; i++){u[i]=0;}
System.arraycopy(c, 0, u, 0, BMAX);
// for(int i=0; i<BMAX+1; i++){x[i]=0;}
System.arraycopy(c, 0, x, 0, BMAX+1);
}
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/InfTree.java
|
Java
|
asf20
| 19,238
|
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class Adler32{
// largest prime smaller than 65536
static final private int BASE=65521;
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
static final private int NMAX=5552;
long adler32(long adler, byte[] buf, int index, int len){
if(buf == null){ return 1L; }
long s1=adler&0xffff;
long s2=(adler>>16)&0xffff;
int k;
while(len > 0) {
k=len<NMAX?len:NMAX;
len-=k;
while(k>=16){
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
s1+=buf[index++]&0xff; s2+=s1;
k-=16;
}
if(k!=0){
do{
s1+=buf[index++]&0xff; s2+=s1;
}
while(--k!=0);
}
s1%=BASE;
s2%=BASE;
}
return (s2<<16)|s1;
}
/*
private java.util.zip.Adler32 adler=new java.util.zip.Adler32();
long adler32(long value, byte[] buf, int index, int len){
if(value==1) {adler.reset();}
if(buf==null) {adler.reset();}
else{adler.update(buf, index, len);}
return adler.getValue();
}
*/
}
|
0359xiaodong-sydy
|
src/com/jcraft/jzlib/Adler32.java
|
Java
|
asf20
| 3,289
|
#!/usr/bin/perl
#
# ConnectBot: simple, powerful, open-source SSH client for Android
# Copyright 2011 Kenny Root, Jeffrey Sharkey
#
# 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.
#
use strict;
use warnings;
use Getopt::Long;
use Pod::Usage;
use LWP::UserAgent;
#use LWP::Debug qw(+);
use HTTP::Cookies;
use HTML::Form;
use Data::Dumper;
use IO::File;
use XML::LibXML;
use Locale::Language;
use Locale::Country;
my %config = (
'url' => undef,
'username' => undef,
'password' => undef,
'build' => undef,
'branch' => undef,
);
my $baseUrl;
my $fileRegex;
sub setupUA() {
my $ua = LWP::UserAgent->new;
push @{ $ua->requests_redirectable }, 'POST';
$ua->cookie_jar(HTTP::Cookies->new);
return $ua;
}
sub getLoginToken($) {
my $ua = shift;
my $response = $ua->get("https://www.google.com/accounts/Login");
my @forms = HTML::Form->parse($response->content, $response->base);
my $f = shift @forms;
$f->param('Email', $config{'username'});
$f->param('Passwd', $config{'password'});
my $req = $f->click();
$response = $ua->request($req);
if (not $response->is_success) {
print "Got the error " . $response->status_line . "\n";
die "cannot login";
}
}
sub uploadFile($$) {
my $ua = shift;
my $targetFile = shift;
# Go to package upload
my $response = $ua->get($baseUrl . "entry");
my @forms = HTML::Form->parse($response->content, $response->base);
my $f = $forms[$#forms];
my $summary = $config{'appname'} . " " . $config{'branch'} . " development snapshot";
if (defined($config{'build'})) {
$summary .= " " . $config{'build'};
}
$f->param('summary', $summary);
$f->param('file', $targetFile);
$f->param('label', 'Type-Installer', 'Featured');
my $req = $f->click('btn');
$response = $ua->request($req);
return ($response->code eq "302");
}
sub unfeature($$) {
my $ua = shift;
my $url = shift;
print "unfeaturing $url\n";
my $response = $ua->get($url);
if (not $response->is_success) {
warn "couldn't reach $url";
return 0;
}
my @forms = HTML::Form->parse($response->content, $response->base);
my $f = $forms[2];
my $i = 0;
my $input = $f->find_input('label', 'text', $i++);
while ($i != -1 and defined($input)) {
if ($input->value eq 'Featured') {
$input->value('');
$i = -1;
} else {
$input = $f->find_input('label', 'text', $i++);
}
}
my $req = $f->click();
$response = $ua->request($req);
if (not $response->is_success) {
warn "unfeature: got the error " . $response->status_line . "\n";
return 0;
}
return 1;
}
sub deleteFile($$) {
my $ua = shift;
my $name = shift;
my $url = $baseUrl . "delete?name=" . $name;
my $response = $ua->get($url);
if (not $response->is_success) {
warn "deleteFile: couldn't reach $url";
return 0;
}
my @forms = HTML::Form->parse($response->content, $response->base);
my $f = $forms[2];
my $req = $f->click('delete');
$response = $ua->request($req);
if (not $response->is_success) {
warn "deleteFile: got the error " . $response->status_line . "\n";
return 0;
}
print "Deleted $name\n";
return 1;
}
sub fixFeatured($) {
my $ua = shift;
my $response = $ua->get($baseUrl . 'list?q=label:Featured');
my $parser = XML::LibXML->new();
$parser->recover(1);
my $doc = $parser->parse_html_string($response->content);
my $root = $doc->getDocumentElement;
my @nodes = $root->findnodes('//table[@id="resultstable"]//td[contains(@class, "col_1") and a[@class="label" and contains(@href, "Featured")]]/a[1]/@href');
foreach my $node (@nodes) {
my $href = $node->findvalue('.');
next if ($href !~ $fileRegex);
unfeature($ua, $baseUrl . $href) if ($2 ne $config{'build'} and $1 eq $config{'branch'});
}
}
sub deleteUndownloaded($$) {
my $ua = shift;
my $threshhold = shift;
my $offset = 0;
my $parser = XML::LibXML->new();
$parser->recover(1);
my @toDelete = ();
while (1) {
my $response = $ua->get($baseUrl . 'list?start=' . $offset);
my $doc = $parser->parse_html_string($response->content);
my $root = $doc->getDocumentElement;
my @nodes = $root->findnodes('//div[contains(., "Your search did not generate any results.")]');
last if $#nodes > -1;
@nodes = $root->findnodes('//table[@id="resultstable"]//tr[@id="headingrow"]/th[starts-with(normalize-space(a), "DownloadCount")]/@class');
die 'Could not find DownloadCount header column' if ($#nodes == -1);
my $downloadCountClass = $nodes[0]->findvalue('.');
@nodes = $root->findnodes('//table[@id="resultstable"]//td[contains(@class, "col_1") and not(a[@class="label" and contains(@href, "Featured")]) and ../td[contains(@class, "'.$downloadCountClass.'") and normalize-space(.) <= "'.$threshhold.'"]]/a[1]/@href');
foreach my $node (@nodes) {
my $href = $node->findvalue('.');
next if ($href !~ $fileRegex);
if ($href =~ /detail\?name=([^&]+)&/) {
push @toDelete, $1;
print "Pushing on $1\n";
}
}
$offset += 100;
}
#foreach my $href (@toDelete) {
# deleteFile($ua, $href);
#}
}
pod2usage(1) if ($#ARGV < 0);
GetOptions(\%config,
'appname=s',
'username=s',
'password=s',
'build=s',
'branch=s',
);
my $projectName = lc($config{'appname'});
$baseUrl = 'http://code.google.com/p/' . $projectName . '/downloads/';
$fileRegex = qr/$config{'appname'}-git-([a-z]*)-([0-9_-]*)(-[a-zA-Z]*)?\.apk/;
my $ua = setupUA();
getLoginToken($ua);
my $file = shift @ARGV;
uploadFile($ua, $file);
fixFeatured($ua);
deleteUndownloaded($ua, 10);
__END__
=head1 NAME
google-code-upload.pl - Upload builds to Google Code
=head1 SYNOPSIS
google-code-upload.pl [options] <file>
=head1 OPTIONS
=over 8
=item B<--username>
Username which has permission to uplaod files.
=item B<--password>
Password for user matching the username.
=item B<--appname>
Name used for the project's name (lowercase) and for matching existing
files in download.
=item B<--build>
Build identifier (e.g., 2011-08-01-0001)
=item B<--branch>
Branch that this build belongs to. Optional.
=back
=head1 DESCRIPTION
B<This program> uploads builds to a Google Code website, features the new
uploads, and unfeatures any old uploades.
=head1 AUTHOR
Kenny Root
=head1 COPYRIGHT and LICENSE
Copyright 2011 Kenny Root, Jeffrey Sharkey
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.
=cut
|
0359xiaodong-sydy
|
tools/google-code-upload.pl
|
Perl
|
asf20
| 7,224
|
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := com_google_ase_Exec
LOCAL_CFLAGS := -Werror
LOCAL_SRC_FILES := com_google_ase_Exec.cpp
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)
|
0359xiaodong-sydy
|
jni/Exec/Android.mk
|
Makefile
|
asf20
| 220
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*/
#include "com_google_ase_Exec.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include "android/log.h"
#define LOG_TAG "Exec"
#define LOG(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
void JNU_ThrowByName(JNIEnv* env, const char* name, const char* msg) {
jclass clazz = env->FindClass(name);
if (clazz != NULL) {
env->ThrowNew(clazz, msg);
}
env->DeleteLocalRef(clazz);
}
char* JNU_GetStringNativeChars(JNIEnv* env, jstring jstr) {
if (jstr == NULL) {
return NULL;
}
jbyteArray bytes = 0;
jthrowable exc;
char* result = 0;
if (env->EnsureLocalCapacity(2) < 0) {
return 0; /* out of memory error */
}
jclass Class_java_lang_String = env->FindClass("java/lang/String");
jmethodID MID_String_getBytes = env->GetMethodID(
Class_java_lang_String, "getBytes", "()[B");
bytes = (jbyteArray) env->CallObjectMethod(jstr, MID_String_getBytes);
exc = env->ExceptionOccurred();
if (!exc) {
jint len = env->GetArrayLength(bytes);
result = (char*) malloc(len + 1);
if (result == 0) {
JNU_ThrowByName(env, "java/lang/OutOfMemoryError", 0);
env->DeleteLocalRef(bytes);
return 0;
}
env->GetByteArrayRegion(bytes, 0, len, (jbyte*) result);
result[len] = 0; /* NULL-terminate */
} else {
env->DeleteLocalRef(exc);
}
env->DeleteLocalRef(bytes);
return result;
}
int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor) {
jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor");
jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor,
"descriptor", "I");
return env->GetIntField(fileDescriptor, descriptor);
}
static int create_subprocess(
const char* cmd, const char* arg0, const char* arg1, int* pProcessId) {
char* devname;
int ptm;
pid_t pid;
ptm = open("/dev/ptmx", O_RDWR); // | O_NOCTTY);
if(ptm < 0){
LOG("[ cannot open /dev/ptmx - %s ]\n", strerror(errno));
return -1;
}
fcntl(ptm, F_SETFD, FD_CLOEXEC);
if(grantpt(ptm) || unlockpt(ptm) ||
((devname = (char*) ptsname(ptm)) == 0)){
LOG("[ trouble with /dev/ptmx - %s ]\n", strerror(errno));
return -1;
}
pid = fork();
if(pid < 0) {
LOG("- fork failed: %s -\n", strerror(errno));
return -1;
}
if(pid == 0){
int pts;
setsid();
pts = open(devname, O_RDWR);
if(pts < 0) exit(-1);
dup2(pts, 0);
dup2(pts, 1);
dup2(pts, 2);
close(ptm);
execl(cmd, cmd, arg0, arg1, NULL);
exit(-1);
} else {
*pProcessId = (int) pid;
return ptm;
}
}
JNIEXPORT jobject JNICALL Java_com_google_ase_Exec_createSubprocess(
JNIEnv* env, jclass clazz, jstring cmd, jstring arg0, jstring arg1,
jintArray processIdArray) {
char* cmd_8 = JNU_GetStringNativeChars(env, cmd);
char* arg0_8 = JNU_GetStringNativeChars(env, arg0);
char* arg1_8 = JNU_GetStringNativeChars(env, arg1);
int procId;
int ptm = create_subprocess(cmd_8, arg0_8, arg1_8, &procId);
if (processIdArray) {
int procIdLen = env->GetArrayLength(processIdArray);
if (procIdLen > 0) {
jboolean isCopy;
int* pProcId = (int*) env->GetPrimitiveArrayCritical(processIdArray, &isCopy);
if (pProcId) {
*pProcId = procId;
env->ReleasePrimitiveArrayCritical(processIdArray, pProcId, 0);
}
}
}
jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor");
jmethodID init = env->GetMethodID(Class_java_io_FileDescriptor,
"<init>", "()V");
jobject result = env->NewObject(Class_java_io_FileDescriptor, init);
if (!result) {
LOG("Couldn't create a FileDescriptor.");
} else {
jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor,
"descriptor", "I");
env->SetIntField(result, descriptor, ptm);
}
return result;
}
JNIEXPORT void Java_com_google_ase_Exec_setPtyWindowSize(
JNIEnv* env, jclass clazz, jobject fileDescriptor, jint row, jint col,
jint xpixel, jint ypixel) {
int fd;
struct winsize sz;
fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
if (env->ExceptionOccurred() != NULL) {
return;
}
sz.ws_row = row;
sz.ws_col = col;
sz.ws_xpixel = xpixel;
sz.ws_ypixel = ypixel;
ioctl(fd, TIOCSWINSZ, &sz);
}
JNIEXPORT jint Java_com_google_ase_Exec_waitFor(JNIEnv* env, jclass clazz,
jint procId) {
int status;
waitpid(procId, &status, 0);
int result = 0;
if (WIFEXITED(status)) {
result = WEXITSTATUS(status);
}
return result;
}
|
0359xiaodong-sydy
|
jni/Exec/com_google_ase_Exec.cpp
|
C++
|
asf20
| 5,383
|
# Build both ARMv5TE and x86-32 machine code.
APP_ABI := armeabi x86
|
0359xiaodong-sydy
|
jni/Application.mk
|
Makefile
|
asf20
| 69
|
include $(call all-subdir-makefiles)
|
0359xiaodong-sydy
|
jni/Android.mk
|
Makefile
|
asf20
| 37
|
<html>
<body style="background-color: #000; color: #fff">
<p>Gestures in ConnectBot allow a user to do several things for
which there's no keyboard equivalent. If the gestures seem
backward, then imagine that you're grabbing the text and moving it
with your finger.</p>
<h1><a name="Page_Up_/_Page_Down" />Page Up / Page Down</h1>
<p>Swiping your finger up and down on the left third of the screen
will send a page up and page down key to the remote host. Many programs
map this to scrolling back into history such as irssi or tinyfugue.</p>
<p><img
src="http://connectbot.googlecode.com/svn/trunk/www/gesture-pgup.png" />
Page Up gesture</p>
<p><img
src="http://connectbot.googlecode.com/svn/trunk/www/gesture-pgdn.png" />
Page Down gesture</p>
<h1><a name="Scroll_back_/_Scroll_forward" />Scroll back / Scroll
forward</h1>
<p>Swiping your finger up on the right side of the screen allows you
to scroll backward and forward in the local terminal buffer history.</p>
<p><img
src="http://connectbot.googlecode.com/svn/trunk/www/gesture-scrollback.png" />
Scroll back gesture</p>
<p><img
src="http://connectbot.googlecode.com/svn/trunk/www/gesture-scrollforward.png" />
Scroll forward gesture</p>
<h1><a name="Switching_hosts" />Switching hosts</h1>
<p>Swiping your finger from one side of the screen to the other will
switch between currently connected hosts.</p>
<p><img
src="http://connectbot.googlecode.com/svn/trunk/www/gesture-hostprev.png" />
Previous host gesture</p>
<p><img
src="http://connectbot.googlecode.com/svn/trunk/www/gesture-hostnext.png" />
Next host gesture</p>
</body>
</html>
|
0359xiaodong-sydy
|
assets/help/ScreenGestures.html
|
HTML
|
asf20
| 1,613
|
<html>
<body style="background-color: #000; color: #fff">
<p><img
src="http://connectbot.googlecode.com/svn/trunk/www/keyboard.jpg" /></p>
<p>Here are some keyboard shortcuts available when a <strong>hardware
keyboard</strong> is present. If you're using a phone where the main input
type is a <strong>virtual keyboard</strong>, please see the VirtualKeyboard help topic.
</p>
<p><strong>Note:</strong> the side that <strong>shift</strong>, <strong>alt</strong>,
<strong>slash</strong>, and <strong>tab</strong> uses can be changed in
preferences between left, right, and disabled.</p>
<ul>
<li>Control key (CTRL)</li>
<blockquote>Pressing once on the trackball will toggle on
<strong>control</strong> for the next character typed. The cursor will
indicate this state with a < symbol. Note that pressing the
trackball again will send an <strong>escape</strong> key.</blockquote>
</ul>
<ul>
<li>Escape (ESC)</li>
<blockquote>Pressing twice on the trackball will send <strong>escape</strong>
key. Note that some other terminal emulators map pressing <strong>ALT-<i>key</i></strong>
to <strong>escape + <i>key</i></strong>.</blockquote>
</ul>
<ul>
<li>Shift</li>
<blockquote>Pressing the <strong>shift</strong> (up arrow)
key once will make the next key typed its uppercase variant according
to the keyboard layout. This state is indicated with an outline of a
triangle on the top of the cursor. Pressing it twice will turn on <strong>shift
lock</strong> which is indicated by a solid triangle on the top of the cursor.</blockquote>
</ul>
<ul>
<li>Alt</li>
<blockquote>Pressing the <strong>Alt</strong> key once
will make the next key typed its symbol as indicated on the keyboard.
This state is indicated with the outline of a triangle on the bottom of
the cursor. Pressing it twice will turn on <strong>alt lock</strong>
which is indicated by a solid triangle on the bottom of the cursor.</blockquote>
</ul>
<ul>
<li>Slash (opposite side Alt)</li>
<blockquote>The opposite side <strong>alt</strong> key can
be used as a shortcut for the forward slash / character. This aids in
quickly typing directories on the G1.</blockquote>
</ul>
<ul>
<li>Tab (opposite side Shift)</li>
<blockquote>The opposite side <strong>shift</strong> key
can be used as a shortcut for the <strong>tab</strong> key (CTRL-i) for
quick completion in many shells.</blockquote>
</ul>
<ul>
<li>Function keys (F1 through F10)</li>
<blockquote>Hold down the shift key and press numbers 1
through 10 to send F1 through F10 respectively.</blockquote>
</ul>
</body>
</html>
|
0359xiaodong-sydy
|
assets/help/PhysicalKeyboard.html
|
HTML
|
asf20
| 2,582
|
<html>
<body style="background-color: #000; color: #fff">
<p><img src="http://connectbot.googlecode.com/svn/trunk/www/magic-cb-screen.png" width="100%" /></p>
<h2>Caveats</h2>
<p>Since ConnectBot doesn't use any of the normal TextView
widgets, Android's IME structure isn't designed to directly
support it.</p>
<p>The best way to use Android with a virtual keyboard is in <strong>Portrait</strong>
mode. By default, ConnectBot is set to use <strong>Portrait</strong>
mode when no hardware keyboard is present. To change this setting, go to
<strong>Preferences</strong> from the <strong>Host List</strong>.</p>
<p>In <strong>Landscape</strong> mode, the Android virtual keyboard
(or other IMEs) will take up the entire screen. Android provides no way
for ConnectBot to resize the terminal view in <strong>Landscape</strong>.
However, you may use a <i>work-around</i>: <strong>Force Resize</strong>
to fit above the virtual keyboard if desired.</p>
<p>On devices without a hardware keyboard, you may press and hold
the <strong>MENU</strong> button to bring up the virtual keyboard. NOTE:
This applies to any program on the Android platform; it is not
ConnectBot specific.</p>
<h2>How to Enter Control, Alt, Escape, and Function Keys</h2>
<p>You can enter any key combination with ConnectBot and the virtual
keyboard, but you must know how keys are mapped on a normal console. For
instance, usually combinations of ALT+letter on a PC keyboard are
actually mapped to sending, sequentially, ESC key then the letter.</p>
<p>Note there are also screen gestures: see the ScreenGestures help topic.</a>
for <strong>Page Up</strong> and <strong>Page Down</strong>.</p>
<ul>
<li>Trackball: 1 press is <strong>CTRL</strong>, 2 presses sends <strong>ESC</strong>
</li>
<li><strong>Tab key</strong> = <strong>CTRL + i</strong></li>
<li><strong>Function key</strong> = <strong>CTRL + number</strong>
</li>
</ul>
<h2>Examples</h2>
<ul>
<li><strong>ESC</strong> = Press the trackball twice.</li>
<li><strong>ALT + Right Arrow</strong> = Press trackball twice
then move trackball to right.</li>
<li><strong>CTRL + A</strong> = Press trackball once then tap the
"A" key on the soft keyboard.</li>
<li><strong>F3</strong> = Press trackball once then tap the
"3" key on the soft keyboard.</li>
</ul>
</body>
</html>
|
0359xiaodong-sydy
|
assets/help/VirtualKeyboard.html
|
HTML
|
asf20
| 2,345
|
<html>
<body style="background-color: #000; color: #fff">
<h2>Helpful hints</h2>
<p>When you have multiple sessions open, you can 'pan' between them by swiping your finger left-to-right or right-to-left over the screen.</p>
<p>Long-press on your Android desktop to create direct shortcuts to frequently-used SSH hosts.</p>
<p>Slide your finger up/down on the right-half of the terminal screen to look at the scrollback history. Slide up/down on the left-half to send the page up/down keys.</p>
</body>
</html>
|
0359xiaodong-sydy
|
assets/help/Hints.html
|
HTML
|
asf20
| 515
|
/* atom.c - implement string atoms.
*/
#include "atom.h"
typedef struct TAtom
{
const char* String;
int RefCount;
unsigned Hash;
struct TAtom* Next;
} TAtom;
static TAtom* FreeList; /* list of free TAtoms */
static TAtom** HashTable; /* hash table of all TAtoms */
static unsigned HashSize; /* size of hash table */
/* AtomNew() - return pointer to empty atom.
*/
static
TAtom* AtomNew(void)
{
TAtom* Result;
/* if freelist is empty, better put something on it */
if(FreeList == NULL)
{
unsigned iAtom;
unsigned BlockCount = (1024*4)/sizeof(TAtom);
FreeList = calloc(BlockCount, sizeof(TAtom));
assert(FreeList != NULL);
/* link together atoms in new block to form new free list */
for(iAtom = 0; iAtom < (BlockCount-1); ++iAtom)
FreeList[iAtom].Next = &FreeList[iAtom+1];
/* first time through, need to allocate hash table */
if(HashTable == NULL)
{
HashSize = 137; /* prime number so mod does some scattering */
HashTable = calloc(HashSize, sizeof(TAtom*));
assert(HashTable != NULL);
}
}
/* now free list is not empty */
Result = FreeList;
FreeList = Result->Next;
return Result;
}
/* HashString() - return hash from string; nothing fancy.
*/
static unsigned HashString(const char* Str)
{
unsigned Hash = 0xFEAD;
while(*Str)
{
Hash = (Hash * 8) ^ *Str++;
}
}
/* AtomCreate() - create a new atom from a string (or find an existing atom!)
*/
ATOM AtomCreate(const char* String)
{
unsigned Hash = HashString(String);
TAtom** Ptr = &HashTable[Hash % HashTableSize];
ATOM Result = NULL;
/* search linked-list in hash table */
while(*Ptr)
{
/* if we found a match */
if((*Ptr)->Hash == Hash && !strcmp(String, (*Ptr)->String))
{
Result = (ATOM)(*Ptr);
break;
}
else
Ptr = &((*Ptr)->Next);
}
if(Result == NULL)
{
TAtom* New = AtomNew();
New->Hash = Hash;
New->String = String;
New->Next = HashTable[Hash % HashTableSize];
Result = (ATOM)New;
break;
}
}
void AtomDeref(ATOM Atom);
ATOM AtomRef(ATOM Atom);
ATOM AtomFind(const char* String);
const char* AtomString(ATOM Atom);
|
100siddhartha-blacc
|
atom.c
|
C
|
mit
| 2,711
|
/* Burk Labs Anachronistic Compiler Compiler (BLACC) v0.0
* Generated from: 'test.blc'
* on: Wed Feb 06 20:47:47 2013
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
extern unsigned GetNextToken(void);
#define BLC_GETINT(Ptr) ((Ptr)[0] | ((Ptr)[1]<<8))
#define BLC_OP_MATCH (0) /* MATCH [token_id] */
#define BLC_OP_CALL (1)
#define BLC_OP_TAILSELECT (2)
#define BLC_OP_LLSELECT (3)
#define BLC_OP_ACTRED (4)
#define BLC_OP_REDUCE (5)
#define BLC_OP_HALT (6)
#define BLC_OP_SHIFTSEL (7)
#define BLC_OP_ACTION8 (8)
#define BLC_OP_LR0 (9)
#ifndef BLC_ASSERT
#define BLC_ASSERT assert
#endif
typedef unsigned char BLC_BYTE;
/* define token identifiers */
#define BLC_EOF (0)
#define BLC_MATCHANY (1)
#define BLC_NOACTION (0)
#define {} (2)
#define TK_FOO (3)
#define TK_INCR (4)
#define TK_DECR (5)
#define TK_IDENT (6)
#define TK_IF (7)
#define TK_ELSE (8)
#define TK_NUMBER (9)
#define TK_SIZEOF (10)
#if SCHAR_MAX >= 94 && SCHAR_MIN <= 0
typedef signed char BLC_TOKVAL;
#elif SHRT_MAX >= 94 && SHRT_MIN <= 0
typedef short BLC_TOKVAL;
#elif INT_MAX >= 94 && INT_MIN <= 0
typedef int BLC_TOKVAL;
#else
typedef long BLC_TOKVAL;
#endif
typedef unsigned char BLC_OPCODE;
typedef int BLC_VALTYPE;
/* Machine is a byte array that contains all the information
* the parser needs to parse the given language.
*/
static BLC_BYTE Machine[195 /* 0x00C3 */] =
{
127,0, /* [ 127] terminal symbol table size */
19,0, /* [ 19] nonterminal symbol table size */
2,0, /* [ 2] entry table size */
16,0, /* [ 16] selection table size */
21,0, /* [ 21] rule opcode table size */
/* Terminal symbol table */
0, /* [ 0] 'BLC_EOF' */
'B', 'L', 'C', 95,
'E', 'O', 'F', 0,
1, /* [ 1] 'BLC_MATCHANY' */
'B', 'L', 'C', 95,
'M', 'A', 'T', 'C',
'H', 'A', 'N', 'Y',
0,
2, /* [ 2] '{}' */
123, 125, 0,
3, /* [ 3] 'TK_FOO' */
'T', 'K', 95, 'F',
'O', 'O', 0,
4, /* [ 4] 'TK_INCR' */
'T', 'K', 95, 'I',
'N', 'C', 'R', 0,
5, /* [ 5] 'TK_DECR' */
'T', 'K', 95, 'D',
'E', 'C', 'R', 0,
6, /* [ 6] 'TK_IDENT' */
'T', 'K', 95, 'I',
'D', 'E', 'N', 'T',
0,
7, /* [ 7] 'TK_IF' */
'T', 'K', 95, 'I',
'F', 0,
8, /* [ 8] 'TK_ELSE' */
'T', 'K', 95, 'E',
'L', 'S', 'E', 0,
9, /* [ 9] 'TK_NUMBER' */
'T', 'K', 95, 'N',
'U', 'M', 'B', 'E',
'R', 0,
10, /* [ 10] 'TK_SIZEOF' */
'T', 'K', 95, 'S',
'I', 'Z', 'E', 'O',
'F', 0,
42, /* [ 42] ''*'' */
39, 42, 39, 0,
43, /* [ 43] ''+'' */
39, 43, 39, 0,
45, /* [ 45] ''-'' */
39, 45, 39, 0,
47, /* [ 47] ''/'' */
39, 47, 39, 0,
94, /* [ 94] ''^'' */
39, 94, 39, 0,
0, /* sentinel byte */
/* Nonterminal symbol table */
/* [0] Start */
'S', 't', 'a', 'r',
't', 0,
/* [1] list */
'l', 'i', 's', 't',
0,
/* [2] idents */
'i', 'd', 'e', 'n',
't', 's', 0,
0, /* sentinel byte */
/* entry table */
0x00,0x00, /* Start */
/* selection table */
/*0x0000: LLSELECT body for 'Start' */
0, /* EOL (no token ranges) */
0, /* EOL (no token lists) */
/*0x0002: LLSELECT body for 'list' */
0, /* EOL (no token ranges) */
2, /* 2 tokens for this rule */
0x06,0x00, /* 0x0006: address of rule */
0, /* BLC_EOF */
6, /* TK_IDENT */
0, /* EOL for token lists */
/*0x0009: LLSELECT body for 'idents' */
0, /* EOL (no token ranges) */
2, /* 2 tokens for this rule */
0x0C,0x00, /* 0x000C: address of rule */
0, /* BLC_EOF */
6, /* TK_IDENT */
0, /* EOL for token lists */
/*0x00AE: Begin opcodes */
/*[0x0000] <start> -> Start BLC_EOF */
0x01, /* BLCOP_CALL Start */
0x0F,0x00,
0x00, /* MATCH BLC_EOF */
0,
0x06, /* HALT */
/*[0x0006] list -> idents {A0} */
0x03, /* BLCOP_LLSELECT idents */
0x09,0x00,
0x04, /* BLCOP_ACTRED {A0} */
0x01, /* rule# */
0x01, /* <argcount> */
/*[0x000C] idents -> {A0} */
0x04, /* BLCOP_ACTRED {A0} */
0x01, /* rule# */
0x00, /* <argcount> */
/*[0x000F] Start -> list {A0} */
0x01, /* BLCOP_CALL list */
0x06,0x00,
0x04, /* BLCOP_ACTRED {A0} */
0x01, /* rule# */
0x01, /* <argcount> */
};
typedef struct BLC_STATE
{
BLC_BYTE* Machine;
BLC_BYTE* TermSymtab;
BLC_BYTE* NontermSymtab;
BLC_BYTE* SelectData;
BLC_BYTE* Opcodes;
unsigned OpcodesSize;
BLC_VALTYPE* ValStack;
BLC_VALTYPE* VSP;
size_t ValStackSize;
BLC_VALTYPE ReturnValue;
unsigned short* Stack;
size_t StackSize;
unsigned SP; /* stack pointer (offset into Stack) */
BLC_BYTE* IP; /* instruction pointer (Opcodes offset) */
unsigned CurrentToken;
int NStates;
unsigned LR0State; /* current state # of LR(0) machine */
} BLC_STATE;
static
const char* BlcTokstr(BLC_BYTE* Symtab, int Token)
{
while(*Symtab != Token)
{
while(*++Symtab)
;
++Symtab; /* skip over NUL terminating byte */
}
/* skip token ID byte */
++Symtab;
return Symtab;
}
#ifndef BLC_PARSER_NAME
#define BLC_PARSER_NAME BlcParse
#endif
#ifndef BLC_NO_PARSER
/* BlcParse() - main parsing loop.
*/
int BLC_PARSER_NAME(void)
{
BLC_STATE State;
unsigned Count;
unsigned Opcode, Value, Address, Offset, ArgCount;
BLC_BYTE* Select;
State.Machine = Machine;
Offset = 10;
State.TermSymtab = State.Machine + Offset;
Offset += BLC_GETINT(State.Machine+0);
State.NontermSymtab = State.Machine + Offset;
Offset += BLC_GETINT(State.Machine+2);
Offset += BLC_GETINT(State.Machine+4);
State.SelectData = State.Machine + Offset;
Offset += BLC_GETINT(State.Machine+6);
printf("opcode offset=0x%04X\n", Offset);
State.Opcodes = State.Machine + Offset;
State.OpcodesSize = BLC_GETINT(State.Machine+8);
State.ValStackSize = 100;
State.ValStack = (BLC_VALTYPE*)calloc(State.ValStackSize, sizeof(BLC_VALTYPE));
State.VSP = State.ValStack;
State.StackSize = 100;
State.Stack = (unsigned short*)calloc(State.StackSize, sizeof(unsigned short));
State.SP = 0;
State.IP = State.Opcodes;
State.CurrentToken = (BLC_BYTE)GetNextToken();
for(;;)
{
unsigned iStack;
printf("[%d,%d]Opcode=0x%02X CurTok=%d(%s) IP=0x%04X [0x%02X 0x%02X 0x%02X 0x%02X]\n",
State.SP, State.VSP - State.ValStack, *State.IP,
State.CurrentToken, BlcTokstr(State.TermSymtab, State.CurrentToken),
(unsigned)(State.IP - State.Opcodes),
State.IP[0], State.IP[1], State.IP[2], State.IP[3]);
printf("[");
for(iStack=0; iStack < State.SP; ++iStack)
printf("0x%04X ", State.Stack[iStack]);
printf("]\n");
Opcode = *State.IP++;
Value = *State.IP++;
switch(Opcode)
{
case BLC_OP_MATCH : /* match a particular token */
printf("MATCH %d (%s)\n", Value, BlcTokstr(State.TermSymtab, Value));
if(Value == State.CurrentToken)
{
*State.VSP++ = Value;
State.CurrentToken = (BLC_BYTE)GetNextToken();
continue;
}
fprintf(stderr, "Expecting token %d (%s), found %d (%s)\n", Value, BlcTokstr(State.TermSymtab, Value), State.CurrentToken, BlcTokstr(State.TermSymtab, State.CurrentToken));
exit(1);
break;
case BLC_OP_CALL : /* [16-bit rule offset] */
Address = Value | (*State.IP++ << 8);
printf("CALL 0x%04X\n", Address);
++State.VSP; /* leave room for $$ */
State.Stack[State.SP++] = (unsigned short)(State.IP - State.Opcodes);
State.IP = State.Opcodes + Address;
break;
case BLC_OP_TAILSELECT : /* for left recursion */
printf("TAILSELECT pops %d from value stack. (SP=%d, VSP=%d)\n", Value, State.SP, State.VSP - State.ValStack);
// State.VSP -= Value;
assert(State.VSP >= State.ValStack);
Value = *State.IP++;
case BLC_OP_LLSELECT :
Address = Value | (*State.IP++ << 8);
printf("Select offset: 0x%04X\n", Address);
Select = State.SelectData + Address;
/* first come the token ranges */
Count = *Select++;
//printf("%d token ranges\n", Count);
while(Count > 0)
{
Address = BLC_GETINT(Select);
//printf("Address: 0x%04X\n", Address);
Select += 2;
while(Count-- > 0)
if(State.CurrentToken >= Select[0] && State.CurrentToken <= Select[1])
goto SelectFound;
else
Select += 2;
Count = *Select++;
}
/* Then we do groups (multiple values, single rule) */
Count = *Select++;
//printf("%d token groups\n", Count);
while(Count > 0)
{
Address = BLC_GETINT(Select);
//printf("Address: 0x%04X\n", Address);
Select += 2;
for(; Count > 0; --Count)
if(*Select++ == State.CurrentToken)
goto SelectFound;
Count = *Select++;
}
/* no match on tail select just means no more tail recursion */
if(Opcode == BLC_OP_TAILSELECT)
{
Value = 0; /* already reduced value stack */
goto Reduce;
}
/* no match for select! */
printf("No match for select!\n");
exit(99);
SelectFound:
printf("SelectFound:\n");
if(Opcode == BLC_OP_TAILSELECT)
{
/* copy $$ -> $1 */
// State.VSP -= TailPop;
assert(State.VSP > State.ValStack);
State.VSP[0] = State.VSP[-1];
printf("++State.VSP\n");
++State.VSP;
}
else
{
assert(State.SP < 99);
/* push address in current rule onto stack */
State.Stack[State.SP++] = (unsigned short)(State.IP - State.Opcodes);
++State.VSP; /* leave room for $$ */
}
State.IP = &State.Opcodes[Address];
break;
case BLC_OP_HALT : /* All done! */
printf("OP_HALT\n");
return 0;
case BLC_OP_SHIFTSEL : /* LR(0) state, non-accepting */
printf("OP_SHIFTSEL\n");
Address = Value | (*State.IP++ << 8); /* address of select data */
State.Stack[State.SP++] = (unsigned short)(State.IP-State.Opcodes); /* address of our GOTO */
break;
case BLC_OP_ACTRED :
case BLC_OP_ACTION8 : /* */
ArgCount = *State.IP++;
if(Opcode == BLC_OP_ACTRED)
State.ReturnValue = State.VSP[-ArgCount];
printf("Perform action %d[%d] XXXXXXXX ", Value, ArgCount);
switch(Value)
{
case 1 :
{
{A0}
}
break;
default :
assert(0); /* got illegal value for action number */
}
if(Opcode == BLC_OP_ACTRED)
{
printf("VSP=%d, ArgCount=%d, %d\n", State.VSP-State.ValStack,ArgCount,-ArgCount-1);
assert(State.VSP-State.ValStack > ArgCount);
State.VSP[-ArgCount-1] = State.ReturnValue;
Value = ArgCount;
}
else
{
State.VSP[0] = State.ReturnValue;
++State.VSP;
continue;
}
case BLC_OP_REDUCE : /* [8-bit symbol count] */
Reduce:
printf("reduce %d (SP=%d, VSP=%d)\n", Value, State.SP, (State.VSP - State.ValStack));
assert(State.SP >= 1);
assert((State.VSP - State.ValStack) >= 0);
assert((State.VSP - State.ValStack) >= Value);
State.VSP -= Value;
if(Opcode == BLC_OP_REDUCE)
State.VSP[0] = State.VSP[1];
if(State.IP[0] != BLC_OP_TAILSELECT)
{
State.SP -= 1;
Address = State.Stack[State.SP];
assert(Address < State.OpcodesSize);
State.IP = State.Opcodes + Address;
}
break;
case BLC_OP_LR0 : /* begin parsing in (modified) LR(0) mode */
printf("BLC_OP_LR0\n");
State.Stack[State.SP++] = 0; /* start in state 0 */
break;
default:
printf("Bad opcode: 0x%02X (%d)\n", Opcode, State.IP[-1]);
exit(99);
}
}
}
#endif
#include <stdio.h>
|
100siddhartha-blacc
|
blcparse.c
|
C
|
mit
| 14,599
|
#ifndef SYMTAB_H_
#define SYMTAB_H_
/*
Our symbol table needs are modest. A symbol is either a terminal or a
non-terminal. We only add items to the symbol table, never remove them.
*/
#ifndef COMMON_H_
# include "common.h"
#endif
#ifndef INPUT_H_
# include "input.h"
#endif
enum
{
SYM_TERMINAL = 0x0001,
SYM_LEFTRECURSIVE = 0x0002,
SYM_FIRSTFOLLOWCLASH = 0x0004,
SYM_NULLABLE = 0x0008,
SYM_USEDINRULE = 0x0010,
SYM_SIMPLE = 0x0020, /* symbol derives only terminals */
SYM_EMPTY = 0x0040, /* symbol derives nothing */
};
struct TRule;
struct TOperator;
struct TStates;
typedef struct SYMBOLS_
{
void* Dummy_;
} SYMBOLS_, *SYMBOLS;
typedef struct TAction
{
int Number; /* numbered from 0..n */
TToken Action; /* contains action text */
int ArgCount; /* how many symbols to left of this action? */
} TAction;
typedef struct TSymAtom /* TSymAtom: the position-invariant aspects of a symbol */
{
TToken Name;
SYMBOLS Definitions;
int BitFlags;
} TSymAtom;
typedef struct TSymbol /* An instance of a symbol */
{
TToken Name;
TToken Lhs;
int Bits;
// int Type; /* TERMINAL or NONTERM */
int Value; /* unique integer value/ID */
int LeftRecursive; /* is this nonterminal left-recursive? */
int PredicateEnd; /* end of implicit syntactic predicate? */
int OperatorTrigger;
int FirstFollowClash;
struct TStates* LR0;
int Nullable; /* symbol can derive epsilon */
int Operand;
int UsedInRule;
SYMBOLS OpAbbrev; /* list of opsyms, if this is operator abbreviation */
// TSymbol* LeftRecursive; /* points to generated symbol after rewrite */
TAction* Action; /* NULL unless symbol is really an action */
SYMBOLS InputTokens;
int* LLTable;
SYMBOLS First;
SYMBOLS Follow;
SYMBOLS EndsWith;
struct TRule** Rules;
struct TRule** OrigRules; /* keep original rules when transforming grammar */
int SelectOffset;
} TSymbol;
typedef struct SymIt /* symbol list iterator */
{
SYMBOLS List;
TSymbol* Symbol;
int Count;
int Index;
} SymIt;
SymIt SymItNew(SYMBOLS List);
int SymbolIterate(SymIt* Info);
enum ItemType { TERMINAL, NONTERM };
enum OperatorType { OP_UNKNOWN, OP_BINARY, OP_PRE_UNARY, OP_POST_UNARY, OP_TRINARY };
void SymbolInit(void);
void SymbolFini(void);
int PatternCmp(const char* Pattern, const char* OpStr);
enum OPSYMFLAGS
{
OPFL_LEFT_BRACKET = 0x0001,
OPFL_RIGHT_BRACKET = 0x0002,
};
typedef struct TOperator
{
TToken Decl;
int IntRep;
int Precedence;
int Associativity;
int Used; /* true if operator used in a production */
const char* Pattern;
int SymCount;
SYMBOLS List;
int Flags;
} TOperator;
typedef struct TRule
{
int RuleId; /* rules are numbered from 0..n */
int Nullable; /* rule can derive epsilon */
int Predicate; /* rule has predicate */
SYMBOLS Symbols; /* Symbols this rule produces (rhs) */
TToken* Tokens; /* for positional info */
int* InLoop; /* TRUE if part of left recursive loop */
SYMBOLS First;
TOperator* Operator;
int ProductionOffset;
int LeftFactor; /* used during left factoring */
struct TRule* LeftRecursive; /* if this is rewrite, points to original rule */
int TailRecursive; /* TRUE if right-recursive grammar rewrite */
} TRule;
typedef struct RuleIt /* Rule iterator */
{
TSymbol* Root;
int NRules;
TRule* Rule;
int iRule;
int NProdItems;
TSymbol* ProdItem;
int iProdItem;
int Finished; /* TRUE while iRule < NRules */
} RuleIt;
RuleIt RuleItNew(TSymbol* Root);
void RuleItNext(RuleIt* Info);
int RuleIterate(RuleIt* Info);
void RuleFree(TRule* Rule);
int RuleCount(TSymbol* Symbol);
int RuleItemCount(TRule* Rule);
SYMBOLS RuleFirst(TSymbol* NonTerm, TRule* Rule, int iProdItem);
int RuleNullable(TRule* Rule, int iProdItem);
int RuleIsNull(TRule* Rule);
TRule* RuleDup(TRule* Rule);
void RuleAddSymbol(TRule* Rule, TSymbol* Symbol, TToken Token);
TSymbol* RuleRemoveSymbol(TRule* Rule, int Pos);
int SymbolIsEqual(TSymbol* A, TSymbol* B);
int SymbolIsNullable(TSymbol* A);
int SymbolSetBit(TSymbol* Symbol, int Bit);
int SymbolGetBit(TSymbol* Symbol, int Bit);
TSymbol* SymbolFind(TToken Token);
TSymbol* SymbolFromValue(int Value);
TSymbol* SymbolSetValue(TSymbol* Symbol, int Value);
TSymbol* SymbolAdd(TToken Token, int Type);
TSymbol* SymbolStart(void);
int SymbolIsAction(TSymbol* Symbol);
int SymbolIsEmpty(TSymbol* Symbol);
int SymbolIsTerminal(TSymbol* Symbol);
int SymbolIsOpSyms(TSymbol* Symbol);
SYMBOLS SymbolGetAllSymbols(TSymbol* Symbol);
TSymbol* SymbolAddStart(TSymbol* StartSymbol);
const char* SymbolStr(TSymbol* Symbol);
TRule* SymbolNewRule(TSymbol* Symbol);
TRule* SymbolAddRule(TSymbol* Symbol, TRule* Rule);
TRule* SymbolDupRule(TSymbol* Symbol, TRule* OldRule);
SYMBOLS SymbolListCreate(void);
//#ifdef MEMWATCH
//# define SymbolListCreate() (SYMBOLS)mwMark((void*)SymbolListCreate(), "symbol list", __FILE__, __LINE__)
//#endif
SYMBOLS SymbolListDestroy(SYMBOLS List);
//#ifdef MEMWATCH
//# define SymbolListDestroy(List) ((List)?(mwUnmark(List, __FILE__, __LINE__),SymbolListDestroy(List)):NULL)
//#endif
SYMBOLS SymbolListAdd(SYMBOLS List, TSymbol* Symbol);
//#ifdef MEMWATCH
#if 0
# define SymbolListAdd(List, Symbol) List?SymbolListAdd(List,Symbol):(SYMBOLS)mwMark(SymbolListAdd(List,Symbol), "SymbolListAdd", __FILE__, __LINE__);
#endif
SYMBOLS SymbolListAddFirst(SYMBOLS List, TSymbol* ProdItem);
int SymbolListAddList(SYMBOLS* List, SYMBOLS Add);
SYMBOLS SymbolListAddUnique(SYMBOLS Handle, TSymbol* Symbol);
SYMBOLS SymbolListCopy(SYMBOLS To, SYMBOLS From);
TSymbol* SymbolListGet(SYMBOLS List, int Index);
int SymbolListEqual(SYMBOLS A, SYMBOLS B);
TSymbol* SymbolListFind(SYMBOLS List, TToken Token);
int SymbolListCount(SYMBOLS List);
int SymbolListCountSig(SYMBOLS List);
int SymbolListIndex(SYMBOLS List, TSymbol* Symbol);
int SymbolListRemove(SYMBOLS List, TSymbol* Symbol);
SYMBOLS SymbolListTruncate(SYMBOLS List, int NewLen);
TSymbol* SymbolListDelete(SYMBOLS List, int Position);
int SymbolListContains(SYMBOLS List, TSymbol* Symbol);
SYMBOLS SymbolListIntersect(SYMBOLS List, SYMBOLS With);
int SymbolListDump(FILE* Handle, SYMBOLS List, const char* Sep);
char* SymbolListDumpStr(SYMBOLS List, const char* Sep);
#define SymbolListPush SymbolListAdd
/* void SymbolListPush(SYMBOLS List, TSymbol* Symbol);*/
TSymbol* SymbolListPop(SYMBOLS List);
TSymbol* SymbolListTop(SYMBOLS List);
SYMBOLS SymbolListReplace(SYMBOLS List, int Pos, SYMBOLS Insert);
TToken Unquote(TToken Token);
TSymbol* LiteralFind(TToken Token);
void LiteralAdd(TSymbol* Symbol, TToken Token);
TToken LiteralFromSymbol(TSymbol* Symbol);
extern TSymbol* EndSymbol;
extern TSymbol* EolSymbol;
extern TSymbol* MatchAnySymbol;
extern TSymbol* NoActionSymbol;
TSymbol* SymbolNewNonTerm(TToken Token);
TSymbol* SymbolNewTerm(TToken Token);
void DumpTreeSymbol(TSymbol* Symbol, int Annotate);
#endif /* SYMTAB_H_ */
|
100siddhartha-blacc
|
symtab.h
|
C
|
mit
| 8,908
|
#include "symlist.h"
typedef struct TSymList
{
TSymbol** Symbols;
int NSymbols;
} TSymList;
|
100siddhartha-blacc
|
symlist.c
|
C
|
mit
| 139
|
/*
** MEMWATCH.H
** Nonintrusive ANSI C memory leak / overwrite detection
** Copyright (C) 1992-2002 Johan Lindh
** All rights reserved.
** Version 2.71
**
************************************************************************
**
** PURPOSE:
**
** MEMWATCH has been written to allow guys and gals that like to
** program in C a public-domain memory error control product.
** I hope you'll find it's as advanced as most commercial packages.
** The idea is that you use it during the development phase and
** then remove the MEMWATCH define to produce your final product.
** MEMWATCH is distributed in source code form in order to allow
** you to compile it for your platform with your own compiler.
** It's aim is to be 100% ANSI C, but some compilers are more stingy
** than others. If it doesn't compile without warnings, please mail
** me the configuration of operating system and compiler you are using
** along with a description of how to modify the source, and the version
** number of MEMWATCH that you are using.
**
************************************************************************
This file is part of MEMWATCH.
MEMWATCH 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.
MEMWATCH 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 MEMWATCH; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
************************************************************************
**
** REVISION HISTORY:
**
** 920810 JLI [1.00]
** 920830 JLI [1.10 double-free detection]
** 920912 JLI [1.15 mwPuts, mwGrab/Drop, mwLimit]
** 921022 JLI [1.20 ASSERT and VERIFY]
** 921105 JLI [1.30 C++ support and TRACE]
** 921116 JLI [1.40 mwSetOutFunc]
** 930215 JLI [1.50 modified ASSERT/VERIFY]
** 930327 JLI [1.51 better auto-init & PC-lint support]
** 930506 JLI [1.55 MemWatch class, improved C++ support]
** 930507 JLI [1.60 mwTest & CHECK()]
** 930809 JLI [1.65 Abort/Retry/Ignore]
** 930820 JLI [1.70 data dump when unfreed]
** 931016 JLI [1.72 modified C++ new/delete handling]
** 931108 JLI [1.77 mwSetAssertAction() & some small changes]
** 940110 JLI [1.80 no-mans-land alloc/checking]
** 940328 JLI [2.00 version 2.0 rewrite]
** Improved NML (no-mans-land) support.
** Improved performance (especially for free()ing!).
** Support for 'read-only' buffers (checksums)
** ^^ NOTE: I never did this... maybe I should?
** FBI (free'd block info) tagged before freed blocks
** Exporting of the mwCounter variable
** mwBreakOut() localizes debugger support
** Allocation statistics (global, per-module, per-line)
** Self-repair ability with relinking
** 950913 JLI [2.10 improved garbage handling]
** 951201 JLI [2.11 improved auto-free in emergencies]
** 960125 JLI [X.01 implemented auto-checking using mwAutoCheck()]
** 960514 JLI [2.12 undefining of existing macros]
** 960515 JLI [2.13 possibility to use default new() & delete()]
** 960516 JLI [2.20 suppression of file flushing on unfreed msgs]
** 960516 JLI [2.21 better support for using MEMWATCH with DLL's]
** 960710 JLI [X.02 multiple logs and mwFlushNow()]
** 960801 JLI [2.22 merged X.01 version with current]
** 960805 JLI [2.30 mwIsXXXXAddr() to avoid unneeded GP's]
** 960805 JLI [2.31 merged X.02 version with current]
** 961002 JLI [2.32 support for realloc() + fixed STDERR bug]
** 961222 JLI [2.40 added mwMark() & mwUnmark()]
** 970101 JLI [2.41 added over/underflow checking after failed ASSERT/VERIFY]
** 970113 JLI [2.42 added support for PC-Lint 7.00g]
** 970207 JLI [2.43 added support for strdup()]
** 970209 JLI [2.44 changed default filename to lowercase]
** 970405 JLI [2.45 fixed bug related with atexit() and some C++ compilers]
** 970723 JLI [2.46 added MW_ARI_NULLREAD flag]
** 970813 JLI [2.47 stabilized marker handling]
** 980317 JLI [2.48 ripped out C++ support; wasn't working good anyway]
** 980318 JLI [2.50 improved self-repair facilities & SIGSEGV support]
** 980417 JLI [2.51 more checks for invalid addresses]
** 980512 JLI [2.52 moved MW_ARI_NULLREAD to occur before aborting]
** 990112 JLI [2.53 added check for empty heap to mwIsOwned]
** 990217 JLI [2.55 improved the emergency repairs diagnostics and NML]
** 990224 JLI [2.56 changed ordering of members in structures]
** 990303 JLI [2.57 first maybe-fixit-for-hpux test]
** 990516 JLI [2.58 added 'static' to the definition of mwAutoInit]
** 990517 JLI [2.59 fixed some high-sensitivity warnings]
** 990610 JLI [2.60 fixed some more high-sensitivity warnings]
** 990715 JLI [2.61 changed TRACE/ASSERT/VERIFY macro names]
** 991001 JLI [2.62 added CHECK_BUFFER() and mwTestBuffer()]
** 991007 JLI [2.63 first shot at a 64-bit compatible version]
** 991009 JLI [2.64 undef's strdup() if defined, mwStrdup made const]
** 000704 JLI [2.65 added some more detection for 64-bits]
** 010502 JLI [2.66 incorporated some user fixes]
** [mwRelink() could print out garbage pointer (thanks mac@phobos.ca)]
** [added array destructor for C++ (thanks rdasilva@connecttel.com)]
** [added mutex support (thanks rdasilva@connecttel.com)]
** 010531 JLI [2.67 fix: mwMutexXXX() was declared even if MW_HAVE_MUTEX was not defined]
** 010619 JLI [2.68 fix: mwRealloc() could leave the mutex locked]
** 020918 JLI [2.69 changed to GPL, added C++ array allocation by Howard Cohen]
** 030212 JLI [2.70 mwMalloc() bug for very large allocations (4GB on 32bits)]
** 030520 JLI [2.71 added ULONG_LONG_MAX as a 64-bit detector (thanks Sami Salonen)]
**
** To use, simply include 'MEMWATCH.H' as a header file,
** and add MEMWATCH.C to your list of files, and define the macro
** 'MEMWATCH'. If this is not defined, MEMWATCH will disable itself.
**
** To call the standard C malloc / realloc / calloc / free; use mwMalloc_(),
** mwCalloc_() and mwFree_(). Note that mwFree_() will correctly
** free both malloc()'d memory as well as mwMalloc()'d.
**
** 980317: C++ support has been disabled.
** The code remains, but is not compiled.
**
** For use with C++, which allows use of inlining in header files
** and class specific new/delete, you must also define 'new' as
** 'mwNew' and 'delete' as 'mwDelete'. Do this *after* you include
** C++ header files from libraries, otherwise you can mess up their
** class definitions. If you don't define these, the C++ allocations
** will not have source file and line number information. Also note,
** most C++ class libraries implement their own C++ memory management,
** and don't allow anyone to override them. MFC belongs to this crew.
** In these cases, the only thing to do is to use MEMWATCH_NOCPP.
**
** You can capture output from MEMWATCH using mwSetOutFunc().
** Just give it the adress of a "void myOutFunc(int c)" function,
** and all characters to be output will be redirected there.
**
** A failing ASSERT() or VERIFY() will normally always abort your
** program. This can be changed using mwSetAriFunc(). Give it a
** pointer to a "int myAriFunc(const char *)" function. Your function
** must ask the user whether to Abort, Retry or Ignore the trap.
** Return 2 to Abort, 1 to Retry or 0 to Ignore. Beware retry; it
** causes the expression to be evaluated again! MEMWATCH has a
** default ARI handler. It's disabled by default, but you can enable
** it by calling 'mwDefaultAri()'. Note that this will STILL abort
** your program unless you define MEMWATCH_STDIO to allow MEMWATCH
** to use the standard C I/O streams. Also, setting the ARI function
** will cause MEMWATCH *NOT* to write the ARI error to stderr. The
** error string is passed to the ARI function instead, as the
** 'const char *' parameter.
**
** You can disable MEMWATCH's ASSERT/VERIFY and/or TRACE implementations.
** This can be useful if you're using a debug terminal or smart debugger.
** Disable them by defining MW_NOASSERT, MW_NOVERIFY or MW_NOTRACE.
**
** MEMWATCH fills all allocated memory with the byte 0xFE, so if
** you're looking at erroneous data which are all 0xFE:s, the
** data probably was not initialized by you. The exception is
** calloc(), which will fill with zero's. All freed buffers are
** zapped with 0xFD. If this is what you look at, you're using
** data that has been freed. If this is the case, be aware that
** MEMWATCH places a 'free'd block info' structure immediately
** before the freed data. This block contains info about where
** the block was freed. The information is in readable text,
** in the format "FBI<counter>filename(line)", for example:
** "FBI<267>test.c(12)". Using FBI's slows down free(), so it's
** disabled by default. Use mwFreeBufferInfo(1) to enable it.
**
** To aid in tracking down wild pointer writes, MEMWATCH can perform
** no-mans-land allocations. No-mans-land will contain the byte 0xFC.
** MEMWATCH will, when this is enabled, convert recently free'd memory
** into NML allocations.
**
** MEMWATCH protects it's own data buffers with checksums. If you
** get an internal error, it means you're overwriting wildly,
** or using an uninitialized pointer.
**
************************************************************************
**
** Note when compiling with Microsoft C:
** - MSC ignores fflush() by default. This is overridden, so that
** the disk log will always be current.
**
** This utility has been tested with:
** PC-lint 7.0k, passed as 100% ANSI C compatible
** Microsoft Visual C++ on Win16 and Win32
** Microsoft C on DOS
** SAS C on an Amiga 500
** Gnu C on a PC running Red Hat Linux
** ...and using an (to me) unknown compiler on an Atari machine.
**
************************************************************************
**
** Format of error messages in MEMWATCH.LOG:
** message: <sequence-number> filename(linenumber), information
**
** Errors caught by MemWatch, when they are detected, and any
** actions taken besides writing to the log file MEMWATCH.LOG:
**
** Double-freeing:
** A pointer that was recently freed and has not since been
** reused was freed again. The place where the previous free()
** was executed is displayed.
** Detect: delete or free() using the offending pointer.
** Action: The delete or free() is cancelled, execution continues.
** Underflow:
** You have written just ahead of the allocated memory.
** The size and place of the allocation is displayed.
** Detect: delete or free() of the damaged buffer.
** Action: The buffer is freed, but there may be secondary damage.
** Overflow:
** Like underflow, but you've written after the end of the buffer.
** Detect: see Underflow.
** Action: see Underflow.
** WILD free:
** An unrecognized pointer was passed to delete or free().
** The pointer may have been returned from a library function;
** in that case, use mwFree_() to force free() of it.
** Also, this may be a double-free, but the previous free was
** too long ago, causing MEMWATCH to 'forget' it.
** Detect: delete or free() of the offending pointer.
** Action: The delete or free() is cancelled, execution continues.
** NULL free:
** It's unclear to me whether or not freeing of NULL pointers
** is legal in ANSI C, therefore a warning is written to the log file,
** but the error counter remains the same. This is legal using C++,
** so the warning does not appear with delete.
** Detect: When you free(NULL).
** Action: The free() is cancelled.
** Failed:
** A request to allocate memory failed. If the allocation is
** small, this may be due to memory depletion, but is more likely
** to be memory fragmentation problems. The amount of memory
** allocated so far is displayed also.
** Detect: When you new, malloc(), realloc() or calloc() memory.
** Action: NULL is returned.
** Realloc:
** A request to re-allocate a memory buffer failed for reasons
** other than out-of-memory. The specific reason is shown.
** Detect: When you realloc()
** Action: realloc() is cancelled, NULL is returned
** Limit fail:
** A request to allocate memory failed since it would violate
** the limit set using mwLimit(). mwLimit() is used to stress-test
** your code under simulated low memory conditions.
** Detect: At new, malloc(), realloc() or calloc().
** Action: NULL is returned.
** Assert trap:
** An ASSERT() failed. The ASSERT() macro works like C's assert()
** macro/function, except that it's interactive. See your C manual.
** Detect: On the ASSERT().
** Action: Program ends with an advisory message to stderr, OR
** Program writes the ASSERT to the log and continues, OR
** Program asks Abort/Retry/Ignore? and takes that action.
** Verify trap:
** A VERIFY() failed. The VERIFY() macro works like ASSERT(),
** but if MEMWATCH is not defined, it still evaluates the
** expression, but it does not act upon the result.
** Detect: On the VERIFY().
** Action: Program ends with an advisory message to stderr, OR
** Program writes the VERIFY to the log and continues, OR
** Program asks Abort/Retry/Ignore? and takes that action.
** Wild pointer:
** A no-mans-land buffer has been written into. MEMWATCH can
** allocate and distribute chunks of memory solely for the
** purpose of trying to catch random writes into memory.
** Detect: Always on CHECK(), but can be detected in several places.
** Action: The error is logged, and if an ARI handler is installed,
** it is executed, otherwise, execution continues.
** Unfreed:
** A memory buffer you allocated has not been freed.
** You are informed where it was allocated, and whether any
** over or underflow has occured. MemWatch also displays up to
** 16 bytes of the data, as much as it can, in hex and text.
** Detect: When MemWatch terminates.
** Action: The buffer is freed.
** Check:
** An error was detected during a CHECK() operation.
** The associated pointer is displayed along with
** the file and line where the CHECK() was executed.
** Followed immediately by a normal error message.
** Detect: When you CHECK()
** Action: Depends on the error
** Relink:
** After a MEMWATCH internal control block has been trashed,
** MEMWATCH tries to repair the damage. If successful, program
** execution will continue instead of aborting. Some information
** about the block may be gone permanently, though.
** Detect: N/A
** Action: Relink successful: program continues.
** Relink fails: program aborts.
** Internal:
** An internal error is flagged by MEMWATCH when it's control
** structures have been damaged. You are likely using an uninitialized
** pointer somewhere in your program, or are zapping memory all over.
** The message may give you additional diagnostic information.
** If possible, MEMWATCH will recover and continue execution.
** Detect: Various actions.
** Action: Whatever is needed
** Mark:
** The program terminated without umarking all marked pointers. Marking
** can be used to track resources other than memory. mwMark(pointer,text,...)
** when the resource is allocated, and mwUnmark(pointer) when it's freed.
** The 'text' is displayed for still marked pointers when the program
** ends.
** Detect: When MemWatch terminates.
** Action: The error is logged.
**
**
************************************************************************
**
** The author may be reached by e-mail at the address below. If you
** mail me about source code changes in MEMWATCH, remember to include
** MW's version number.
**
** Johan Lindh
** johan@linkdata.se
**
** The latest version of MEMWATCH may be downloaded from
** http://www.linkdata.se/
*/
#ifndef __MEMWATCH_H
#define __MEMWATCH_H
/* Make sure that malloc(), realloc(), calloc() and free() are declared. */
/*lint -save -e537 */
#include <stdlib.h>
/*lint -restore */
#ifdef __cplusplus
extern "C" {
#endif
/*
** Constants used
** All MEMWATCH constants start with the prefix MW_, followed by
** a short mnemonic which indicates where the constant is used,
** followed by a descriptive text about it.
*/
#define MW_ARI_NULLREAD 0x10 /* Null read (to start debugger) */
#define MW_ARI_ABORT 0x04 /* ARI handler says: abort program! */
#define MW_ARI_RETRY 0x02 /* ARI handler says: retry action! */
#define MW_ARI_IGNORE 0x01 /* ARI handler says: ignore error! */
#define MW_VAL_NEW 0xFE /* value in newly allocated memory */
#define MW_VAL_DEL 0xFD /* value in newly deleted memory */
#define MW_VAL_NML 0xFC /* value in no-mans-land */
#define MW_VAL_GRB 0xFB /* value in grabbed memory */
#define MW_TEST_ALL 0xFFFF /* perform all tests */
#define MW_TEST_CHAIN 0x0001 /* walk the heap chain */
#define MW_TEST_ALLOC 0x0002 /* test allocations & NML guards */
#define MW_TEST_NML 0x0004 /* test all-NML areas for modifications */
#define MW_NML_NONE 0 /* no NML */
#define MW_NML_FREE 1 /* turn FREE'd memory into NML */
#define MW_NML_ALL 2 /* all unused memory is NML */
#define MW_NML_DEFAULT 0 /* the default NML setting */
#define MW_STAT_GLOBAL 0 /* only global statistics collected */
#define MW_STAT_MODULE 1 /* collect statistics on a module basis */
#define MW_STAT_LINE 2 /* collect statistics on a line basis */
#define MW_STAT_DEFAULT 0 /* the default statistics setting */
/*
** MemWatch internal constants
** You may change these and recompile MemWatch to change the limits
** of some parameters. Respect the recommended minimums!
*/
#define MW_TRACE_BUFFER 2048 /* (min 160) size of TRACE()'s output buffer */
#define MW_FREE_LIST 64 /* (min 4) number of free()'s to track */
/*
** Exported variables
** In case you have to remove the 'const' keyword because your compiler
** doesn't support it, be aware that changing the values may cause
** unpredictable behaviour.
** - mwCounter contains the current action count. You can use this to
** place breakpoints using a debugger, if you want.
*/
#ifndef __MEMWATCH_C
extern const unsigned long mwCounter;
#endif
/*
** System functions
** Normally, it is not nessecary to call any of these. MEMWATCH will
** automatically initialize itself on the first MEMWATCH function call,
** and set up a call to mwAbort() using atexit(). Some C++ implementations
** run the atexit() chain before the program has terminated, so you
** may have to use mwInit() or the MemWatch C++ class to get good
** behaviour.
** - mwInit() can be called to disable the atexit() usage. If mwInit()
** is called directly, you must call mwTerm() to end MemWatch, or
** mwAbort().
** - mwTerm() is usually not nessecary to call; but if called, it will
** call mwAbort() if it finds that it is cancelling the 'topmost'
** mwInit() call.
** - mwAbort() cleans up after MEMWATCH, reports unfreed buffers, etc.
*/
void mwInit( void );
void mwTerm( void );
void mwAbort( void );
/*
** Setup functions
** These functions control the operation of MEMWATCH's protective features.
** - mwFlushNow() causes MEMWATCH to flush it's buffers.
** - mwDoFlush() controls whether MEMWATCH flushes the disk buffers after
** writes. The default is smart flushing: MEMWATCH will not flush buffers
** explicitly until memory errors are detected. Then, all writes are
** flushed until program end or mwDoFlush(0) is called.
** - mwLimit() sets the allocation limit, an arbitrary limit on how much
** memory your program may allocate in bytes. Used to stress-test app.
** Also, in virtual-memory or multitasking environs, puts a limit on
** how much MW_NML_ALL can eat up.
** - mwGrab() grabs up X kilobytes of memory. Allocates actual memory,
** can be used to stress test app & OS both.
** - mwDrop() drops X kilobytes of grabbed memory.
** - mwNoMansLand() sets the behaviour of the NML logic. See the
** MW_NML_xxx for more information. The default is MW_NML_DEFAULT.
** - mwStatistics() sets the behaviour of the statistics collector. See
** the MW_STAT_xxx defines for more information. Default MW_STAT_DEFAULT.
** - mwFreeBufferInfo() enables or disables the tagging of free'd buffers
** with freeing information. This information is written in text form,
** using sprintf(), so it's pretty slow. Disabled by default.
** - mwAutoCheck() performs a CHECK() operation whenever a MemWatch function
** is used. Slows down performance, of course.
** - mwCalcCheck() calculates checksums for all data buffers. Slow!
** - mwDumpCheck() logs buffers where stored & calc'd checksums differ. Slow!!
** - mwMark() sets a generic marker. Returns the pointer given.
** - mwUnmark() removes a generic marker. If, at the end of execution, some
** markers are still in existence, these will be reported as leakage.
** returns the pointer given.
*/
void mwFlushNow( void );
void mwDoFlush( int onoff );
void mwLimit( long bytes );
unsigned mwGrab( unsigned kilobytes );
unsigned mwDrop( unsigned kilobytes );
void mwNoMansLand( int mw_nml_level );
void mwStatistics( int level );
void mwFreeBufferInfo( int onoff );
void mwAutoCheck( int onoff );
void mwCalcCheck( void );
void mwDumpCheck( void );
void * mwMark( void *p, const char *description, const char *file, unsigned line );
void * mwUnmark( void *p, const char *file, unsigned line );
/*
** Testing/verification/tracing
** All of these macros except VERIFY() evaluates to a null statement
** if MEMWATCH is not defined during compilation.
** - mwIsReadAddr() checks a memory area for read privilige.
** - mwIsSafeAddr() checks a memory area for both read & write privilige.
** This function and mwIsReadAddr() is highly system-specific and
** may not be implemented. If this is the case, they will default
** to returning nonzero for any non-NULL pointer.
** - CHECK() does a complete memory integrity test. Slow!
** - CHECK_THIS() checks only selected components.
** - CHECK_BUFFER() checks the indicated buffer for errors.
** - mwASSERT() or ASSERT() If the expression evaluates to nonzero, execution continues.
** Otherwise, the ARI handler is called, if present. If not present,
** the default ARI action is taken (set with mwSetAriAction()).
** ASSERT() can be disabled by defining MW_NOASSERT.
** - mwVERIFY() or VERIFY() works just like ASSERT(), but when compiling without
** MEMWATCH the macro evaluates to the expression.
** VERIFY() can be disabled by defining MW_NOVERIFY.
** - mwTRACE() or TRACE() writes some text and data to the log. Use like printf().
** TRACE() can be disabled by defining MW_NOTRACE.
*/
int mwIsReadAddr( const void *p, unsigned len );
int mwIsSafeAddr( void *p, unsigned len );
int mwTest( const char *file, int line, int mw_test_flags );
int mwTestBuffer( const char *file, int line, void *p );
int mwAssert( int, const char*, const char*, int );
int mwVerify( int, const char*, const char*, int );
/*
** User I/O functions
** - mwTrace() works like printf(), but dumps output either to the
** function specified with mwSetOutFunc(), or the log file.
** - mwPuts() works like puts(), dumps output like mwTrace().
** - mwSetOutFunc() allows you to give the adress of a function
** where all user output will go. (exeption: see mwSetAriFunc)
** Specifying NULL will direct output to the log file.
** - mwSetAriFunc() gives MEMWATCH the adress of a function to call
** when an 'Abort, Retry, Ignore' question is called for. The
** actual error message is NOT printed when you've set this adress,
** but instead it is passed as an argument. If you call with NULL
** for an argument, the ARI handler is disabled again. When the
** handler is disabled, MEMWATCH will automatically take the
** action specified by mwSetAriAction().
** - mwSetAriAction() sets the default ARI return value MEMWATCH should
** use if no ARI handler is specified. Defaults to MW_ARI_ABORT.
** - mwAriHandler() is an ANSI ARI handler you can use if you like. It
** dumps output to stderr, and expects input from stdin.
** - mwBreakOut() is called in certain cases when MEMWATCH feels it would
** be nice to break into a debugger. If you feel like MEMWATCH, place
** an execution breakpoint on this function.
*/
void mwTrace( const char* format_string, ... );
void mwPuts( const char* text );
void mwSetOutFunc( void (*func)(int) );
void mwSetAriFunc( int (*func)(const char*) );
void mwSetAriAction( int mw_ari_value );
int mwAriHandler( const char* cause );
void mwBreakOut( const char* cause );
/*
** Allocation/deallocation functions
** These functions are the ones actually to perform allocations
** when running MEMWATCH, for both C and C++ calls.
** - mwMalloc() debugging allocator
** - mwMalloc_() always resolves to a clean call of malloc()
** - mwRealloc() debugging re-allocator
** - mwRealloc_() always resolves to a clean call of realloc()
** - mwCalloc() debugging allocator, fills with zeros
** - mwCalloc_() always resolves to a clean call of calloc()
** - mwFree() debugging free. Can only free memory which has
** been allocated by MEMWATCH.
** - mwFree_() resolves to a) normal free() or b) debugging free.
** Can free memory allocated by MEMWATCH and malloc() both.
** Does not generate any runtime errors.
*/
void* mwMalloc( size_t, const char*, int );
void* mwMalloc_( size_t );
void* mwRealloc( void *, size_t, const char*, int );
void* mwRealloc_( void *, size_t );
void* mwCalloc( size_t, size_t, const char*, int );
void* mwCalloc_( size_t, size_t );
void mwFree( void*, const char*, int );
void mwFree_( void* );
char* mwStrdup( const char *, const char*, int );
/*
** Enable/disable precompiler block
** This block of defines and if(n)defs make sure that references
** to MEMWATCH is completely removed from the code if the MEMWATCH
** manifest constant is not defined.
*/
#ifndef __MEMWATCH_C
#ifdef MEMWATCH
#define mwASSERT(exp) while(mwAssert((int)(exp),#exp,__FILE__,__LINE__))
#ifndef MW_NOASSERT
#ifndef ASSERT
#define ASSERT mwASSERT
#endif /* !ASSERT */
#endif /* !MW_NOASSERT */
#define mwVERIFY(exp) while(mwVerify((int)(exp),#exp,__FILE__,__LINE__))
#ifndef MW_NOVERIFY
#ifndef VERIFY
#define VERIFY mwVERIFY
#endif /* !VERIFY */
#endif /* !MW_NOVERIFY */
#define mwTRACE mwTrace
#ifndef MW_NOTRACE
#ifndef TRACE
#define TRACE mwTRACE
#endif /* !TRACE */
#endif /* !MW_NOTRACE */
/* some compilers use a define and not a function */
/* for strdup(). */
#ifdef strdup
#undef strdup
#endif
#define malloc(n) mwMalloc(n,__FILE__,__LINE__)
#define strdup(p) mwStrdup(p,__FILE__,__LINE__)
#define realloc(p,n) mwRealloc(p,n,__FILE__,__LINE__)
#define calloc(n,m) mwCalloc(n,m,__FILE__,__LINE__)
#define free(p) mwFree(p,__FILE__,__LINE__)
#define CHECK() mwTest(__FILE__,__LINE__,MW_TEST_ALL)
#define CHECK_THIS(n) mwTest(__FILE__,__LINE__,n)
#define CHECK_BUFFER(b) mwTestBuffer(__FILE__,__LINE__,b)
#define MARK(p) mwMark(p,#p,__FILE__,__LINE__)
#define UNMARK(p) mwUnmark(p,__FILE__,__LINE__)
#else /* MEMWATCH */
#define mwASSERT(exp)
#ifndef MW_NOASSERT
#ifndef ASSERT
#define ASSERT mwASSERT
#endif /* !ASSERT */
#endif /* !MW_NOASSERT */
#define mwVERIFY(exp) exp
#ifndef MW_NOVERIFY
#ifndef VERIFY
#define VERIFY mwVERIFY
#endif /* !VERIFY */
#endif /* !MW_NOVERIFY */
/*lint -esym(773,mwTRACE) */
#define mwTRACE /*lint -save -e506 */ 1?(void)0:mwDummyTraceFunction /*lint -restore */
#ifndef MW_NOTRACE
#ifndef TRACE
/*lint -esym(773,TRACE) */
#define TRACE mwTRACE
#endif /* !TRACE */
#endif /* !MW_NOTRACE */
extern void mwDummyTraceFunction(const char *,...);
/*lint -save -e652 */
#define mwDoFlush(n)
#define mwPuts(s)
#define mwInit()
#define mwGrab(n)
#define mwDrop(n)
#define mwLimit(n)
#define mwTest(f,l)
#define mwSetOutFunc(f)
#define mwSetAriFunc(f)
#define mwDefaultAri()
#define mwNomansland()
#define mwStatistics(f)
#define mwMark(p,t,f,n) (p)
#define mwUnmark(p,f,n) (p)
#define mwMalloc(n,f,l) malloc(n)
#define mwStrdup(p,f,l) strdup(p)
#define mwRealloc(p,n,f,l) realloc(p,n)
#define mwCalloc(n,m,f,l) calloc(n,m)
#define mwFree(p) free(p)
#define mwMalloc_(n) malloc(n)
#define mwRealloc_(p,n) realloc(p,n)
#define mwCalloc_(n,m) calloc(n,m)
#define mwFree_(p) free(p)
#define mwAssert(e,es,f,l)
#define mwVerify(e,es,f,l) (e)
#define mwTrace mwDummyTrace
#define mwTestBuffer(f,l,b) (0)
#define CHECK()
#define CHECK_THIS(n)
#define CHECK_BUFFER(b)
#define MARK(p) (p)
#define UNMARK(p) (p)
/*lint -restore */
#endif /* MEMWATCH */
#endif /* !__MEMWATCH_C */
#ifdef __cplusplus
}
#endif
#if 0 /* 980317: disabled C++ */
/*
** C++ support section
** Implements the C++ support. Please note that in order to avoid
** messing up library classes, C++ support is disabled by default.
** You must NOT enable it until AFTER the inclusion of all header
** files belonging to code that are not compiled with MEMWATCH, and
** possibly for some that are! The reason for this is that a C++
** class may implement it's own new() function, and the preprocessor
** would substitute this crucial declaration for MEMWATCH new().
** You can forcibly deny C++ support by defining MEMWATCH_NOCPP.
** To enble C++ support, you must be compiling C++, MEMWATCH must
** be defined, MEMWATCH_NOCPP must not be defined, and finally,
** you must define 'new' to be 'mwNew', and 'delete' to be 'mwDelete'.
** Unlike C, C++ code can begin executing *way* before main(), for
** example if a global variable is created. For this reason, you can
** declare a global variable of the class 'MemWatch'. If this is
** is the first variable created, it will then check ALL C++ allocations
** and deallocations. Unfortunately, this evaluation order is not
** guaranteed by C++, though the compilers I've tried evaluates them
** in the order encountered.
*/
#ifdef __cplusplus
#ifndef __MEMWATCH_C
#ifdef MEMWATCH
#ifndef MEMWATCH_NOCPP
extern int mwNCur;
extern const char *mwNFile;
extern int mwNLine;
class MemWatch {
public:
MemWatch();
~MemWatch();
};
void * operator new(size_t);
void * operator new(size_t,const char *,int);
void * operator new[] (size_t,const char *,int); // hjc 07/16/02
void operator delete(void *);
#define mwNew new(__FILE__,__LINE__)
#define mwDelete (mwNCur=1,mwNFile=__FILE__,mwNLine=__LINE__),delete
#endif /* MEMWATCH_NOCPP */
#endif /* MEMWATCH */
#endif /* !__MEMWATCH_C */
#endif /* __cplusplus */
#endif /* 980317: disabled C++ */
#endif /* __MEMWATCH_H */
/* EOF MEMWATCH.H */
|
100siddhartha-blacc
|
memwatch.h
|
C++
|
mit
| 31,809
|
/* lex.cpp - implement lexing.
*
* Lex acts like a global singleton that retains in-memory copies
* of
****/
#include "lex.h"
#include <fstream>
// keep constants in private namespace
namespace
{
const size_t IO_SIZE = (1024*16); // grow by this much, as needed
const size_t FIRST_READ = (IO_SIZE * 16); // size of our (big!) first read attempt
const long MAX_FILE_SIZE = (1024*1024*8); // I doubt we could handle 8MB worth of grammar!
}
unique_ptr<char> TToken::Unquote() const
{
assert(Type == Lex::QUOTED);
unique_ptr<char> Result(new char[TextLen-1]);
strncpy(Result.get(), Text+1, TextLen-2);
return Result;
}
TToken TToken::Null = { nullptr, 0, 0 };
int TToken::IsNull()
{
return Text == nullptr && TextLen == 0 && Type == 0;
}
LexFile::LexFile(const char* Path, TFileChars Text, TToken FromInclude_)
: Filename(Path), FileText(std::move(Text)), ErrorCount(0), FromInclude(FromInclude_)
{
}
// defaults do all the work
LexFile::~LexFile()
{
}
// TRover: a reference to a pointer to const chars.
typedef char const * & TRover;
/* GetComment() - we hit a '/' followed by a '/' or '*'
*/
void GetComment(TRover Rover, TToken& Token)
{
Token.Type = Lex::COMMENT;
if(*Rover++ == '/') // if single-line comment
{
for(; *Rover; ++Rover)
if(*Rover == '\n')
break;
}
else // else it's a multi-line style comment
{
for(; *Rover; ++Rover)
if(Rover[0] == '*' && Rover[1] == '/')
break;
}
if(*Rover == '\0')
{
// TODO: use line number when context stuff is working!
ErrorExit(ERROR_EOF_IN_COMMENT, "Unexpected EOF in comment.\n");
}
}
int GetDirective(TRover Rover, TToken& Token)
{
int State = 0;
while(isalpha((unsigned char)*Rover++))
;
if(Rover - Token.Text < TToken::MAXLEN)
{
int Len = int(Rover - Token.Text);
if(Len == 5 && !strncmp("%left", Token.Text, 5))
Token.Type = Lex::LEFT, State = 1;
else if(Len == 6 && !strncmp("%right", Token.Text, 6))
Token.Type = Lex::RIGHT, State = 1;
else if(Len == 9 && !strncmp("%nonassoc", Token.Text, 9))
Token.Type = Lex::NONASSOC, State = 1;
else if(Len == 6 && !strncmp("%token", Token.Text, 6))
Token.Type = Lex::TOKEN;
else if(Len == 8 && !strncmp("%operand", Token.Text, 8))
Token.Type = Lex::OPERAND;
else if(Len == 5 && !strncmp("%test", Token.Text, 5))
Token.Type = Lex::TEST;
else if(Len == 6 && !strncmp("%start", Token.Text, 6))
Token.Type = Lex::START;
else
Token.Type = Lex::UNKDIR;
}
return State;
}
void GetWhite(TRover Rover, TToken& Token)
{
Token.Type = Lex::WHITESPACE;
while(strchr(" \t\r\v\f", *Rover))
++Rover;
}
int GetIdent(char const* &Rover, TToken& Token)
{
while(isalnum((unsigned char)*Rover) || *Rover == '_')
++Rover;
Token.Type = Lex::IDENT;
return 0;
}
typedef char* charp;
/* GetNextToken1() - handling operator precedence
*/
int GetNextToken1(char const * &Rover, TToken& Token)
{
char Char;
int State = 1;
Token.Text = Rover;
Token.Type = Lex::NOTUSED;
if((Char=*Rover++) == '\0')
{
Token.Type = Lex::TKEOF;
--Rover;
State = -1;
}
else if(isalpha((unsigned char)Char) || Char == '_')
State = GetIdent(Rover, Token);
else if(strchr(" \t\r\v\f", Char))
GetWhite(Rover, Token);
else if(Char == '/' && (*Rover == '/' || *Rover == '*'))
GetComment(Rover, Token);
else if(Char == '%')
State = GetDirective(Rover, Token);
else
{
switch(Char)
{
case '\n' : Token.Type = Lex::NEWLINE; break;
case '|' : Token.Type = Lex::ORBAR; break;
case ';' : Token.Type = Lex::SEMICOLON; break;
default :
Token.Type = Lex::ILLEGAL;
}
}
if(Rover - Token.Text > TToken::MAXLEN)
{
Token.Type = Lex::TOOLONG;
Token.TextLen = TToken::MAXLEN;
}
else
Token.TextLen = (short)(Rover - Token.Text);
if(Token.Type == Lex::NOTUSED)
fprintf(stderr, "rover=%10.10s\n", Token.Text);
assert(Token.Type != Lex::NOTUSED);
return State;
}
/* GetNextToken0() - normal state of tokenizing.
*/
int GetNextToken0(TRover Rover, TToken& Token)
{
char Char;
int State;
State = 0;
Token.Text = Rover;
Token.Type = Lex::NOTUSED;
if((Char=*Rover++) == '\0')
{
Token.Type = Lex::TKEOF;
--Rover;
State = -1;
}
else if(isalpha((unsigned char)Char) || Char == '_')
State = GetIdent(Rover, Token);
else if(strchr(" \t\r\v\f", Char))
GetWhite(Rover, Token);
else if(Char == '/' && (*Rover == '/' || *Rover == '*'))
GetComment(Rover, Token);
else if(Char == '%')
State = GetDirective(Rover, Token);
else
{
switch(Char)
{
case '\n' : Token.Type = Lex::NEWLINE; break;
case '|' : Token.Type = Lex::ORBAR; break;
case ';' : Token.Type = Lex::SEMICOLON; break;
default :
Token.Type = Lex::ILLEGAL;
}
}
if(Rover - Token.Text > TToken::MAXLEN)
{
Token.Type = Lex::TOOLONG;
Token.TextLen = TToken::MAXLEN;
}
else
Token.TextLen = (short)(Rover - Token.Text);
if(Token.Type == Lex::NOTUSED)
fprintf(stderr, "rover=%10.10s\n", Token.Text);
assert(Token.Type != Lex::NOTUSED);
return State;
}
/* Tokenize() - break input file into tokens.
*
* Returns the number of error tokens encountered. Note that we will
* tokenize successfully, no matter what. Anything bad is just viewed
* as an error token, which is still a token!
*/
typedef int (*STATEFUNC)(TRover Rover, TToken& Token);
int LexFile::Tokenize()
{
char* Rover = &(*FileText)[0]; // get raw pointer
int SectionCount = 0;
TToken Token;
int State = 0; // start state
STATEFUNC Machine[] = { GetNextToken0, GetNextToken1 };
assert(Tokens.size() == 0); // don't call us more than once!
assert(Rover != nullptr);
ErrorCount = 0;
Tokens.reserve(64);
while((State=Machine[State]((TRover)Rover, Token)) >= 0)
{
Tokens.push_back(Token);
switch(Token.Type)
{
case Lex::ILLEGAL :
case Lex::TOOLONG :
case Lex::BADQUOTE : ++ErrorCount;
break;
case Lex::SECTION : ++SectionCount;
break;
}
}
return ErrorCount;
}
/* Lex::FileLoad() - reads contents of Filename to create new LexFile.
*
* Lex is the owner of all such LexFile objects. If a particular file
* was already loaded in the past, we just return a reference to that
* LexFile.
*/
TTokenizedFile Lex::FileLoad(const char* Filename, TToken FromInclude)
{
// caller must check for already loaded file
assert(Files.count(Filename) == 0);
TFileChars FileText(::FileLoad(Filename));
// store it in our map until shutdown time
Files[Filename] = unique_ptr<LexFile>(new LexFile(Filename, std::move(FileText), FromInclude));
// return pointer to loaded file
return Files[Filename].get();
}
TTokenizedFile Lex::Loaded(const char* Filename)
{
std::map<std::string, std::unique_ptr<LexFile> >::iterator Iter;
Iter = Files.find(Filename);
if(Iter == Files.end())
return nullptr;
else
return Iter->second.get();
}
Lex::Lex()
{
}
Lex::~Lex()
{
}
#if 0
char* FileLoad(const char *filename)
{
// open in binary, don't want line ending transformations
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in)
{
in.seekg(0, std::ios::end);
auto Size = in.tellg();
char* contents = new char[(size_t)Size+1];
in.seekg(0, std::ios::beg);
in.read(&contents[0], Size);
in.close();
return(contents);
}
throw(errno);
}
#endif
/* FileLoad() - load the contents of a file into a NUL-terminated string.
*
* There is some funky stuff about standard library file seeking designed
* to permit files larger than you have an integral type for. However,
* our speed drops more than linearly with grammar size, so it's not a
* bad idea to object to being handed a too-large file (e.g., they passed
* us the name of an executable by mistake or something). So, we kill two
* birds with one stone by defining a maximum file size that still fits
* in 32 bits.
*/
static void Resize(const char* Filename, std::vector<char>& Buffer, size_t NewSize)
{
try {
Buffer.resize(NewSize);
}
catch(std::bad_alloc)
{
ErrorExit(ERROR_INPUT_FILE_TOO_BIG,
"Unable to allocate %luKB for reading file '%s' (is it huge?)\n",
(unsigned long)(NewSize / 1024), Filename);
}
}
unique_ptr<std::vector<char>> FileLoad(const char* Filename)
{
unique_ptr<std::vector<char>> Result(new std::vector<char>);
std::vector<char>& Buffer = *Result.get();
size_t LogicalSize = 0;
size_t PhysicalSize = 0;
size_t BytesRead = 0;
assert(Filename != NULL);
assert((IO_SIZE % 512) == 0); // nobody does weird sector sizes, right?
// use exception-safe pointer to hold file handle
unique_ptr<FILE, int(*)(FILE*)> FilePtr(nullptr, fclose);
FilePtr.reset(fopen(Filename, "r"));
if(FilePtr == nullptr)
ErrorExit(ERROR_CANT_OPEN_INPUT_FILE,
"Unable to open '%s' for reading.\n"
"%d: %s\n", Filename, errno, strerror(errno));
for(;;)
{
PhysicalSize = PhysicalSize ? (PhysicalSize+IO_SIZE) : FIRST_READ;
/* +1 is to allow for adding a trailing NUL byte */
Resize(Filename, Buffer, PhysicalSize+1);
BytesRead = fread((void*)(&Buffer[0]+LogicalSize), sizeof(char), IO_SIZE, FilePtr.get());
LogicalSize+= BytesRead;
if(BytesRead != IO_SIZE)
{
/* check for errors first */
if(ferror(FilePtr.get()))
ErrorExit(ERROR_UNKNOWN_FREAD_ERROR,
"Unknown fread() error while reading '%s'\n", Filename);
/* if we hit the end, then we're done */
else if(feof(FilePtr.get()))
{
Buffer[LogicalSize] = '\0';
break; // the only normal exit from the loop!
}
else
ErrorExit(ERROR_FREAD_FELL_SHORT,
"Can't happen: fread() fell short with no errors before EOF.\n");
}
}
// shrink it back down to minimum needed size.
Resize(Filename, Buffer, LogicalSize+1);
return Result;
}
|
100siddhartha-blacc
|
lex.cpp
|
C++
|
mit
| 11,848
|
/* map.h - simple associative container API */
#ifndef MAP_H_
#define MAP_H_
#include <stdlib.h>
typedef int (*TMapCompare)(void* A, size_t ALen, void* B, size_t BLen);
typedef struct MAP_
{
int Dummy_;
} MAP_, *MAP;
MAP MapCreate(TMapCompare Compare);
void* MapFind(MAP Map, void* Key, size_t KeyLen);
void* MapAdd(MAP Map, void* Key, size_t KeyLen, void* Value);
#endif /* MAP_H_ */
|
100siddhartha-blacc
|
map.h
|
C
|
mit
| 441
|
#
# Microsoft nmake Makefile for BLACC
#
#
DEBUGALL=/RTC1 /MDd /DMEMDEBUG
#CPPFLAGS=/Zi /W4 /D_HAS_EXCEPTIONS=0 /D_CRT_SECURE_NO_DEPRECATE /nologo /GF /TP /GS- /EHs-c- /RTCu
CPPFLAGS=/Zi /W4 /D_CRT_SECURE_NO_DEPRECATE /nologo /GF /TP /GS- $(DEBUGALL) /EHsc /analyze
#OBJDIR =obj
EXENAME =blacc
OBJS =main.obj common.obj globals.obj file.obj lex.obj
# symbol.obj common.obj symtab.obj input.obj parse.obj \
# check.obj compute.obj operator.obj loadfile.obj generate.obj map.obj \
# gen_c.obj html.obj memwatch.obj bitset.obj #lr0.obj
# gen_c.obj
LNLIBS =
all : cstr $(EXENAME) TAGS
main.obj : common.h file.h lex.h
common.obj : common.h
file.obj : common.h file.h
globals.obj : common.h
lex.obj : common.h file.h lex.h
# I'm using Gnu Global to maintain tags for Gnu Emacs
TAGS : *.cpp *.h *.str
gtags
cstr : cstr.exe
cstr.exe : cstr.obj
$(EXENAME) : $(EXENAME).exe
if exist memwatch.log del memwatch.log
regress : regress.exe
#regress.exe : $(OBJDIR)\regress.exe
# copy $(OBJDIR)\regress.exe .
regress.exe : regress.obj
main.obj check.obj compute.obj : check.h
$(OBJS) : common.h
main.obj compute.obj : compute.h
generate.obj gen_c.obj : generate.h
input.obj : input.h
main.obj check.obj compute.obj operator.obj parse.obj : parse.h
main.obj check.obj common.obj compute.obj generate.obj gen_c.obj html.obj lr0.obj operator.obj parse.obj symtab.obj : symtab.h input.h
$(EXENAME).exe : $(OBJS)
link /DEBUG /out:$(EXENAME).exe $(OBJS)
gen_c.obj : gen_ctmp.c
html.obj : htmlform.c
htmlform.c : htmlform.str cstr.exe
cstr htmlform.str
gen_ctmp.c : gen_ctmp.str cstr.exe
cstr gen_ctmp.str
clean :
del $(OBJDIR)\*.obj $(OBJDIR)\*.pdb $(OBJDIR)\*.ilk *.map *.out *.not *.ndx *.exe *.com *.bak *.lst *.tmp *.obj *.ilk *.pdb
|
100siddhartha-blacc
|
makefile
|
Makefile
|
mit
| 1,924
|
#ifndef BITSET_H_
#define BITSET_H_
#include <stddef.h>
typedef struct _BITSET
{
void* _Dummy;
} _BITSET, *BITSET;
typedef struct BITITER
{
BITSET BitSet;
int Index;
} BITITER;
BITSET BitSetNew(size_t Size);
void BitSetDelete(BITSET Handle);
BITSET BitSetOr(BITSET Handle, BITSET Other);
BITSET BitSetCopy(BITSET Handle, BITSET Other);
BITSET BitSetSet(BITSET Handle, int Offset);
int BitSetCount(BITSET Handle);
BITITER BitIterNew(BITSET Handle);
int BitIterNext(BITITER* Iter);
#endif /* BITSET_H_ */
|
100siddhartha-blacc
|
bitset.h
|
C
|
mit
| 620
|
#ifndef MICROSOFT_H_
#define MICROSOFT_H_
// Possibly enable memory leak detection under Microsoft Visual C++
#define MicrosoftDebug()
//#ifdef _MSC_VER
#if 0
# ifdef _DEBUG
# define _CRTDBG_MAP_ALLOC
# include <stdlib.h>
# include <crtdbg.h>
# undef MicrosoftDebug // change MicrosoftDebug from empty macro to real function
void MicrosoftDebug(void);
# define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
# define new DEBUG_NEW
# endif
#endif
#endif /* MICROSOFT_H_ */
|
100siddhartha-blacc
|
microsoft.h
|
C
|
mit
| 552
|
#include "javascrp.h"
#define TOKEN_GROW (16)
typedef struct TMarkup
{
int Classes;
int Id;
TToken Token;
} TMarkup;
static TMarkup* Tokens;
static int TokenCount;
static int TokenSize;
static
void GrowTokens(void)
{
int NewSize = TokenSize + TOKEN_GROW;
Tokens = realloc(Tokens, NewSize * sizeof(TMarkup));
assert(Tokens != NULL);
TokenSize = NewSize;
}
void JsAdd(TToken Token)
{
if(TokenCount >= TokenSize)
GrowTokens();
Tokens[TokenCount++].Token = Token;
}
static
int compare(const void* A, const void* B)
{
ptrdiff_t Diff;
Diff = ((TMarkup*)A)->Token.Text - ((TMarkup*)B)->Token.Text;
if(Diff < 0)
return -1;
else if(Diff == 0)
return 0;
else
return 1;
}
static
int FindToken(TToken Token)
{
TMarkup* Found;
Found = bsearch(Token.Text, Tokens, TokenCount, sizeof(TMarkup), compare);
if(Found)
return (int)((TMarkup*)Found - Tokens);
else
return -1;
}
void JsMarkClass(TToken Token, int Class)
{
}
void JsMarkId(TToken Token, int Id)
{
}
static
void FrameSymbols(FILE* Out)
{
}
static
void FrameSource(FILE* Out)
{
}
void JsWrite(const char* Filename)
{
FILE* Out;
Out = fopen(Filename, "w");
fprintf(Out, "<html><head></head><frameset cols=\"25%,*\">\n");
fprintf(Out, " <frame name=\"symbols\">\n");
FrameSymbols(Out);
fprintf(Out, " </frame>\n");
fprintf(Out, " <frame name=\"source\">\n");
FrameSource(Out);
fprintf(Out, " </frame>\n");
fprintf(Out, "</frameset></html>\n");
fclose(Out);
}
|
100siddhartha-blacc
|
javascrp.c
|
C
|
mit
| 1,860
|
#ifndef ATOM_H_
#define ATOM_H_
/* atom.h - interface to string atoms.
*
*/
/* ATOM - opaque handle to a string atom. */
typedef struct ATOM_
{
void* Dummy;
} ATOM_, *ATOM;
ATOM AtomCreate(const char* String, int AutoFree);
void AtomDeref(ATOM Atom);
ATOM AtomRef(ATOM Atom);
ATOM AtomFind(const char* String);
const char* AtomString(ATOM Atom);
#endif /* ATOM_H_ */
|
100siddhartha-blacc
|
atom.h
|
C
|
mit
| 440
|
#include "common.h"
#include <string>
#include <map>
#include <memory>
struct TToken;
class LexedFile
{
char* Load(const char* Filename);
friend class Lex;
LexedFile(const char* Filename);
private:
~LexedFile();
LexedFile(const LexedFile& Other); // disallow: private and no definition
LexedFile& operator=(const LexedFile& Other); // disallow: private and no definition
struct Deleter{void operator()(LexedFile*File) const {delete File;}};
std::string Filename; // name of file
char* Buffer; // complete text of file
TToken* Tokens; // array of tokens (result of tokenizing Buffer)
int ErrorCount; // # of error tokens in Tokens
LexedFile* ParentFile; // file that caused us to be loaded (or NULL)
};
class Lex
{
public:
Lex();
~Lex();
LexedFile& FileLoad(const char* Filename);
private:
std::map<std::string, std::unique_ptr<LexedFile, LexedFile::Deleter>> Files;
};
#if 0
LexedFile::~LexedFile()
{
}
Lex::Lex()
{
}
Lex::~Lex()
{
// Files.clear();
}
void main(void)
{
Lex ThisLex;
}
#endif
|
100siddhartha-blacc
|
foo.cpp
|
C++
|
mit
| 1,311
|
#include "symtab.h"
#include "operator.h"
#include "parse.h"
#include "map.h"
#include "globals.h"
/* We use a dumb, simple hash table to look up symbols.
* The table size is a prime number, since modulo a prime
* is itself a nice distributor of values. 97 should be
* fine for up to several hundred symbols. Realistically,
* a linear search of a table would probably be fast
* enough for most situations BLACC is likely to
* encounter.
*/
#define HASH_TABLE_SIZE (97)
typedef struct TList
{
TSymbol** Symbols;
int NSymbols;
} TList;
/* buffer used by SymbolStr() */
static
char* StrBuffer;
static
SYMBOLS HashTable[HASH_TABLE_SIZE];
/* PatternCmp() - implement patterns for, well, operator patterns.
*
* Returns the position of the given pattern within an operator pattern.
* Returns -1 if no match. Pattern operators include:
* '^' - matches start of string.
* '$' - matches end of string.
* '*' - matches any number of any kind of character.
*/
static int Match(const char* Pattern, const char* OpStr);
int PatternCmp(const char* Pattern, const char* OpStr)
{
int Result = -1; /* assume failure */
int StartPos, Len;
int LeftAnchor=FALSE;
const char* P = Pattern;
Len = (int)strlen(OpStr);
if(*P == '^')
{
LeftAnchor = TRUE;
++P;
}
for(StartPos=0; StartPos < Len; ++StartPos)
{
if(Match(P, OpStr+StartPos))
{
Result = StartPos;
break;
}
if(LeftAnchor)
break;
}
// DumpVerbose("PatternCmp('%s', '%s') = %d\n", Pattern, OpStr, Result);
return Result;
}
/* Match() - simple recursive pattern matcher that does the real work.
*/
static
int Match(const char* Pattern, const char* OpStr)
{
int PatChar, OpChar;
const char* Rover;
for(;;)
{
PatChar = *Pattern;
if(PatChar == '\0') /* if we got to end, then success! */
return TRUE;
OpChar = *OpStr;
switch(PatChar)
{
case '*':
assert(Pattern[1] != '*');
assert(Pattern[1] != '?');
for(Rover=OpStr; ; ++Rover)
{
if(Match(Pattern+1, Rover))
return TRUE;
if(*Rover == '\0')
break;
}
return FALSE;
case '$' :
assert(Pattern[1] == '\0');
return OpChar == '\0';
case '?' : /* should not encounter this here */
assert(FALSE);
break;
default:
if(PatChar != OpChar)
{
if(Pattern[0] && Pattern[1] == '?')
++Pattern;
else
return FALSE;
}
else if(PatChar == '\0')
return TRUE;
else
++Pattern, ++OpStr;
if(*Pattern == '?')
++Pattern;
}
}
}
/* Literals - strings associated with terminals.
The user can use the %token directive to associate a literal
string with the name of a terminal symbol, like so:
%token TK_INCR '++'
This feature is required to make use of the operator precedence
features of BLACC, like so:
%right ++X
The preceding statement declares that there is a unary prefix
operator with right associativity, and that the name of that
operator can be found by looking in the literal pool under
'++'.
*/
typedef struct TLiteral
{
TToken Literal;
TSymbol* Terminal;
} TLiteral;
static
int NLiterals;
static
TLiteral* Literals;
static
TSymbol* StartSymbol;
TSymbol* EndSymbol;
TSymbol* EolSymbol;
TSymbol* MatchAnySymbol;
TSymbol* NoActionSymbol;
TSymbol* ReduceSymbol;
/* SymbolInit() - initialize symbol table.
*
* There are a few symbols we need predefined. This
* function gets them into the symbol table.
*/
void SymbolInit(void)
{
/* hack: EndSymbol defined first so it will get assigned value of 0 */
EndSymbol = SymbolNewTerm(EOFToken);
// EolSymbol = SymbolNewTerm(EOLToken);
MatchAnySymbol = SymbolNewTerm(MatchAnyToken);
NoActionSymbol = SymbolNewTerm(NoActionToken);
ReduceSymbol = SymbolNewTerm(ReduceToken);
}
static
void SymbolFree(TSymbol* Symbol)
{
TRule** Rover;
if(Symbol->InputTokens)
SymbolListDestroy(Symbol->InputTokens);
if(Symbol->First)
SymbolListDestroy(Symbol->First);
if(Symbol->Follow)
SymbolListDestroy(Symbol->Follow);
if(Symbol->EndsWith)
SymbolListDestroy(Symbol->EndsWith);
if(Symbol->LLTable)
free(Symbol->LLTable);
#if 0
if(Symbol->Name.Text && InputIsFake(Symbol->Name))
{
printf("Fake Token: %p '%s'\n", Symbol->Name.Text, SymbolStr(Symbol));
free((void*)Symbol->Name.Text);
}
#endif
Rover = Symbol->Rules;
if(Rover)
{
while(*Rover)
{
RuleFree(*Rover);
++Rover;
}
free(Symbol->Rules);
}
mwUnmark(Symbol, __FILE__, __LINE__);
free(Symbol);
}
void RuleFree(TRule* Rule)
{
SymbolListDestroy(Rule->Symbols);
SymbolListDestroy(Rule->First);
if(Rule->Tokens)
free((void*)Rule->Tokens);
free(Rule);
}
/* SymbolFini() - shut down the symbol table.
*
* This exists merely to get a clean bill of health from
* memwatch.
*/
void SymbolFini(void)
{
int iHash, iSym;
SymbolListDestroy(Globals.Terminals);
SymbolListDestroy(Globals.NonTerms);
if(StrBuffer)
free(StrBuffer);
for(iHash=0; iHash < HASH_TABLE_SIZE; ++iHash)
{
TSymbol* Symbol;
SYMBOLS List = HashTable[iHash];
if(List)
{
for(iSym=0; (Symbol=SymbolListGet(List, iSym)) != NULL; ++iSym)
SymbolFree(Symbol);
SymbolListDestroy(List);
}
}
if(Literals)
free(Literals);
}
int SymbolIsEqual(TSymbol* A, TSymbol* B)
{
// ??? TODO: revise later
return A == B;
}
/*TSymbol* StartSymbol; */
/* SymbolNewNonTerm() - create a new non-terminal data structure.
*
* We assume someone else has already verified that no symbol
* with this name already exists.
*/
TSymbol* SymbolNewNonTerm(TToken Token)
{
TSymbol* Result;
Result = SymbolAdd(Token, !SYM_TERMINAL);
Globals.NonTerms = SymbolListAdd(Globals.NonTerms, Result);
return Result;
}
/* SymbolNewTerm() - create a new terminal data structure.
*
* We assume someone else has already verified that no symbol
* with this name already exists.
*/
TSymbol* SymbolNewTerm(TToken Token)
{
TSymbol* Result;
if(SymbolFind(Token))
ErrorExit(ERROR_TERM_ALREADY_DEFINED, "Terminal already defined: '%.*s'\n",
Token.TextLen, Token.Text);
Result = SymbolAdd(Token, SYM_TERMINAL);
assert(Result != NULL);
Globals.Terminals = SymbolListAdd(Globals.Terminals, Result);
/* Bit of a hack, but we'll set ->First here.
* the FIRST() set of a terminal is just the terminal
*/
Result->First = SymbolListAdd(Result->First, Result);
return Result;
}
/* SymbolListContains() - does the symbol list already contain this symbol?
*
* If it does, we return the index plus 1, which is used elsewhere.
*/
int SymbolListContains(SYMBOLS Handle, TSymbol* Symbol)
{
TList* List = (TList*)Handle;
int Result = FALSE;
if(List)
{
int iList;
for(iList = 0; iList < List->NSymbols; ++iList)
if(List->Symbols[iList] == Symbol)
{
Result = iList + 1;
break;
}
}
return Result;
}
/* SymbolListAddFirst() - add FIRST list of symbol to existing list.
*
*/
SYMBOLS SymbolListAddFirst(SYMBOLS List, TSymbol* ProdItem)
{
/* FIRST(X) is just X, if X is a terminal */
if(SymbolGetBit(ProdItem, SYM_TERMINAL))
List = SymbolListAddUnique(List, ProdItem);
/* otherwise, we have to add one set of symbols to another */
else if(ProdItem->First)
SymbolListAddList(&List, ProdItem->First);
return List;
}
/* SymbolListCopy() - copy one list to another.
*
* It's OK if To is NULL, SymbolListCopy() will create and
* return a new list. If both To and From are NULL, the function
* returns NULL.
*/
SYMBOLS SymbolListCopy(SYMBOLS To, SYMBOLS From)
{
int iSymbol;
TSymbol* Symbol;
if(To == NULL && SymbolListCount(From))
To = SymbolListCreate();
SymbolListTruncate(To, 0);
for(iSymbol=0; (Symbol=SymbolListGet(From, iSymbol)) != NULL; ++iSymbol)
To = SymbolListAdd(To, Symbol);
return To;
}
/* SymbolListAddUnique() - add symbol only if it's not already in list.
*/
SYMBOLS SymbolListAddUnique(SYMBOLS Handle, TSymbol* Symbol)
{
if(!SymbolListContains(Handle, Symbol))
Handle = SymbolListAdd(Handle, Symbol);
return Handle;
}
/* SymbolListRemove() - remove any/all occurrences of a given symbol.
*/
int SymbolListRemove(SYMBOLS Handle, TSymbol* Symbol)
{
int RemoveCount = 0;
int iList;
TList* List;
if(Handle != NULL)
{
List = (TList*)Handle;
for(iList = 0; iList < List->NSymbols; ++iList)
{
TSymbol* This = List->Symbols[iList];
if(This == Symbol)
{
int iNext = iList+1;
if(iNext < List->NSymbols)
memmove(&List->Symbols[iList], &List->Symbols[iNext],
sizeof(TSymbol*)*(List->NSymbols - iNext));
--List->NSymbols;
--iList;
}
}
}
return RemoveCount;
}
/* SymbolListReplace() - replace one symbol with a list of symbols.
*/
SYMBOLS SymbolListReplace(SYMBOLS List, int Pos, SYMBOLS Insert)
{
int iSymbol, nSymbols;
SYMBOLS New = NULL;
nSymbols = SymbolListCount(List);
for(iSymbol=0; iSymbol < Pos && iSymbol < nSymbols; ++iSymbol)
New = SymbolListAdd(New, SymbolListGet(List, iSymbol));
nSymbols = SymbolListCount(Insert);
for(iSymbol=0; iSymbol < nSymbols; ++iSymbol)
New = SymbolListAdd(New, SymbolListGet(Insert, iSymbol));
nSymbols = SymbolListCount(List);
for(iSymbol=Pos+1; iSymbol < nSymbols; ++iSymbol)
New = SymbolListAdd(New, SymbolListGet(List, iSymbol));
List = SymbolListCopy(List, New);
SymbolListDestroy(New);
return List;
}
/* SymbolStr() - return a null-terminated string for the symbol name.
*
* I should, of course, burn in hell for this, but I got tired of the
* tedious and never-ending coding of this form:
* printf("'%.*s'\n", NonTerm->Name.TextLen, NonTerm->Name.Text);
* This function is technically "unsafe" because the returned strings
* are eventually overwritten. Just don't use it except to obtain
* a temporary result for printf()-style functions and it'll do fine.
*/
const char* SymbolStr(TSymbol* Symbol)
{
static char* Rover;
static char* Sentinel;
char* Result;
int Len;
if(StrBuffer == NULL)
{
StrBuffer = malloc(1024*8);
assert(StrBuffer != NULL);
Rover = StrBuffer;
Sentinel = StrBuffer + 1024*8;
}
if(Symbol)
Len = Symbol->Name.TextLen + 1;
else
Len = strlen("(NULL)") + 1;
if(Rover + Len >= Sentinel)
Rover = StrBuffer;
assert(Rover + Len < Sentinel);
if(Symbol)
sprintf(Rover, "%.*s", Symbol->Name.TextLen, Symbol->Name.Text);
else
strcpy(Rover, "(NULL)");
Result = Rover;
Rover += Len;
return Result;
}
TSymbol* SymbolListDelete(SYMBOLS Handle, int Position)
{
TSymbol* Result;
int Next;
TList* List;
assert(Handle != NULL);
List = (TList*)Handle;
assert(Position >= 0);
assert(Position < List->NSymbols);
Result = List->Symbols[Position];
Next = Position+1;
if(Next < List->NSymbols)
memmove(&List->Symbols[Position], &List->Symbols[Next],
sizeof(TSymbol*)*(List->NSymbols - Next));
--List->NSymbols;
return Result;
}
SYMBOLS SymbolListTruncate(SYMBOLS List, int NewLen)
{
while(SymbolListCount(List) > NewLen)
SymbolListDelete(List, NewLen);
return List;
}
/* SymbolListIntersect() - return the intersection of two TSymbol* lists.
*
* Only tricky part is that either list could be NULL.
*/
SYMBOLS SymbolListIntersect(SYMBOLS A, SYMBOLS B)
{
int iSym;
TSymbol* Symbol;
SYMBOLS Result = NULL;
if(A && B)
for(iSym = 0; iSym < SymbolListCount(A); ++iSym)
{
Symbol = SymbolListGet(A, iSym);
if(SymbolListContains(B, Symbol))
Result = SymbolListAddUnique(Result, Symbol);
}
return Result;
}
/* SymbolListAddList() - add second list to first.
*
* In this case, the "lists" are really sets. We only
* add symbols from the second set that are not already in
* the first set. The return value is true if any new symbols
* were added.
*/
int SymbolListAddList(SYMBOLS* List, SYMBOLS Add)
{
int Result = FALSE;
SymIt Symbols = SymItNew(Add);
while(SymbolIterate(&Symbols))
if(!SymbolListContains(*List, Symbols.Symbol))
{
*List = SymbolListAdd(*List, Symbols.Symbol);
Result = TRUE;
}
return Result;
}
/* SymbolListEqual() - are two lists equivalent?
*
* This is just a simple, sequential compare.
*/
int SymbolListEqual(SYMBOLS A, SYMBOLS B)
{
int Result = FALSE; /* assume they won't be equal */
int ACount, BCount;
int iSymbol;
ACount = SymbolListCount(A);
BCount = SymbolListCount(B);
if(ACount == BCount)
{
for(iSymbol = 0; iSymbol < ACount; ++iSymbol)
if(SymbolListGet(A, iSymbol) != SymbolListGet(B, iSymbol))
break;
if(iSymbol >= ACount)
Result = TRUE;
}
return Result;
}
/* SymbolListGet() - get an symbol from a SYMBOLS list.
*
* It is benign to give us an invalid index; we merely
* return NULL.
*/
TSymbol* SymbolListGet(SYMBOLS Handle, int Index)
{
TSymbol* Result = NULL;
TList* List;
List = (TList*)Handle;
if(List)
{
if(Index >= 0 && Index < List->NSymbols)
Result = List->Symbols[Index];
}
return Result;
}
TSymbol* SymbolListFind(SYMBOLS Handle, TToken Token)
{
TSymbol* Result = NULL;
TList* List;
int iSymbol;
List = (TList*)Handle;
if(List)
for(iSymbol = 0; iSymbol < List->NSymbols; ++iSymbol)
if(TokenEqual(Token, List->Symbols[iSymbol]->Name))
{
Result = List->Symbols[iSymbol];
break;
}
return Result;
}
/* SymbolListDumpStr() - print list of symbols into string.
*
* Useful both in debugging output, and for creating nice comments
* in generated code.
*/
char* SymbolListDumpStr(SYMBOLS List, const char* Sep)
{
char* Buffer;
char* Rover;
int iSymbol, NSymbols = 0;
Buffer = malloc(1000);
Buffer[0] = '\0';
Rover = Buffer;
if(List)
{
TSymbol* Symbol;
NSymbols = SymbolListCount(List);
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
{
Symbol = SymbolListGet(List, iSymbol);
sprintf(Rover, "%s", iSymbol ? Sep : "");
Rover += strlen(Rover);
if(Symbol == NULL)
sprintf(Rover, "X");
else if(SymbolIsAction(Symbol))
sprintf(Rover, "{}");
else
sprintf(Rover, "%.*s",
Symbol->Name.TextLen, Symbol->Name.Text);
}
}
return Buffer;
}
#if 0
int SymbolListDumpf(FILE* Handle, const char* Format, SYMBOLS List, ...)
{
int iSymbol, NSymbols = 0;
if(List)
{
TSymbol* Symbol;
NSymbols = SymbolListCount(List);
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
{
Symbol = SymbolListGet(List, iSymbol);
fprintf(Handle, "%s", iSymbol ? Sep : "");
if(Symbol == NULL)
fprintf(Handle, "X");
else if(SymbolIsAction(Symbol))
fprintf(Handle, "{}");
else
fprintf(Handle, "%.*s",
Symbol->Name.TextLen, Symbol->Name.Text);
}
}
return NSymbols;
}
#endif
/* SymbolListDump() - print out a list of symbols.
*
* Useful both in debugging output, and for creating nice comments
* in generated code.
*/
int SymbolListDump(FILE* Handle, SYMBOLS List, const char* Sep)
{
int iSymbol, NSymbols = 0;
int And = FALSE;
int NoActions = FALSE;
int Last;
if(List)
{
TSymbol* Symbol;
if(*Sep == '{')
{
NoActions = TRUE;
++Sep;
}
/* if special separator */
if(!strcmp(Sep, ",and"))
{
And = TRUE;
Sep = ", ";
}
NSymbols = SymbolListCount(List);
/* locate last (printing) symbol */
if(NoActions)
{
Last = -1;
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
if(!SymbolIsAction(SymbolListGet(List, iSymbol)))
Last = iSymbol;
}
else
Last = NSymbols-1;
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
{
const char* Text;
const char* ThisSep = Sep;
Symbol = SymbolListGet(List, iSymbol);
if(NoActions && SymbolIsAction(Symbol))
continue;
if(iSymbol == 0)
ThisSep = "";
else if(And && iSymbol == Last)
ThisSep = ", and ";
fputs(ThisSep, Handle);
if(Symbol == NULL)
Text = "X";
else
Text = SymbolStr(Symbol);
fputs(Text, Handle);
}
}
return NSymbols;
}
int SymbolListIndex(SYMBOLS Handle, TSymbol* Symbol)
{
int Result = -1;
TList* List;
int iSymbol;
List = (TList*)Handle;
if(List)
for(iSymbol = 0; iSymbol < List->NSymbols; ++iSymbol)
if(Symbol == List->Symbols[iSymbol])
{
Result = iSymbol;
break;
}
return Result;
}
int SymbolListCount(SYMBOLS Handle)
{
TList* List;
List = (TList*)Handle;
return List ? List->NSymbols : 0;
}
/* SymbolListCountSig() - count "significant" (non-actions) in list.
*/
int SymbolListCountSig(SYMBOLS Handle)
{
TList* List = (TList*)Handle;
int Result = 0;
if(List)
{
int iList;
for(iList = 0; iList < List->NSymbols; ++iList)
if(!SymbolIsAction(List->Symbols[iList]))
++Result;
}
return Result;
}
/* SymbolListTop() - return symbol on top of stack.
*/
TSymbol* SymbolListTop(SYMBOLS Handle)
{
TList* List;
TSymbol* Result = NULL;
assert(Handle != NULL);
List = (TList*)Handle;
if(List->NSymbols)
{
List->NSymbols;
Result = List->Symbols[List->NSymbols-1];
}
return Result;
}
TSymbol* SymbolListPop(SYMBOLS Handle)
{
TList* List;
TSymbol* Result = NULL;
assert(Handle != NULL);
List = (TList*)Handle;
if(List->NSymbols)
{
--List->NSymbols;
Result = List->Symbols[List->NSymbols];
}
return Result;
}
static
MAP MapIdToSymbol;
static
int CompareSymId(void* A, size_t ALen, void* B, size_t BLen)
{
assert(ALen == 0 && BLen == 0);
return (int)A != (int)B;
}
TSymbol* SymbolFromValue(int Value)
{
TSymbol* Result = NULL;
if(MapIdToSymbol)
Result = (TSymbol*)MapFind(MapIdToSymbol, (void*)Value, 0);
printf("SymbolFromValue(%d)='%s'\n", Value,
Result ? SymbolStr(Result) : "");
return Result;
}
TSymbol* SymbolSetValue(TSymbol* Symbol, int Value)
{
TSymbol* Result = Symbol;
if(MapIdToSymbol == NULL)
{
MapIdToSymbol = MapCreate(CompareSymId);
assert(MapIdToSymbol != NULL);
}
Result = (TSymbol*)MapAdd(MapIdToSymbol, (void*)Value, 0, (void*)Symbol);
assert(Result == Symbol);
Symbol->Value = Value;
return Result;
}
SymIt SymItNew(SYMBOLS List)
{
SymIt Result = {NULL, NULL, -1, -1};
Result.List = List;
Result.Count = SymbolListCount(List);
return Result;
}
int SymbolIterate(SymIt* Info)
{
int Result = FALSE;
Info->Count = SymbolListCount(Info->List);
if(++Info->Index < Info->Count)
{
Result = TRUE;
Info->Symbol = SymbolListGet(Info->List, Info->Index);
}
return Result;
}
RuleIt RuleItNew(TSymbol* Root)
{
RuleIt Result = {0};
Result.Root = Root;
Result.NRules = RuleCount(Root);
Result.iRule = -1;
return Result;
}
/* RuleIterate() - iterate across a symbol's rules.
*
* The start condition is that all the indices are 0 except for
* iRule, which is -1. That makes iProdItem equal to NProdItems (both 0),
* which causes an immediate advance to the next rule by incrementing
* iRule, which sets it to 0.
*/
int RuleIterate(RuleIt* Info)
{
int Result = FALSE;
if(!Info->Finished) /* don't even start if this iteration already completed */
{
++Info->iProdItem; /* advance to new symbol */
/* while current rule is exhausted */
while(Info->iProdItem > Info->NProdItems - 1)
{
if(++Info->iRule >= Info->NRules)
break;
Info->Rule = Info->Root->Rules[Info->iRule];
Info->iProdItem = 0;
Info->NProdItems= SymbolListCount(Info->Rule->Symbols);
}
/* if iteration not completed yet */
if(Info->iRule < Info->NRules)
{
Result = TRUE;
Info->ProdItem = SymbolListGet(Info->Rule->Symbols, Info->iProdItem);
}
}
Info->Finished = (Result == FALSE);
return Result;
}
/* RuleItNext() - advance to next rule in interation.
*/
void RuleItNext(RuleIt* Info)
{
Info->iProdItem = Info->NProdItems;
}
/* RuleCount() - count the # of rules a symbol has.
*
* It's a null-terminated array of pointers.
*/
int RuleCount(TSymbol* Symbol)
{
int Result = 0;
TRule** RulePtr;
RulePtr = Symbol->Rules;
if(RulePtr)
while(*RulePtr++)
++Result;
return Result;
}
#if 0
int RuleCmp(TSymbol* NonTerm, SYMBOLS AList, SYMBOLS BList)
{
int iA, nA, iB, nB;
TSymbol* A;
TSymbol* B;
SYMBOLS Common = NULL;
int MatchCount;
int ActionCount, FoundActions, LastSymbolMatched;
printf(". RuleCmp('%s') comparing rules:\n. -> ", SymbolStr(NonTerm));
SymbolListDump(stdout, AList, " ");
printf("\n. -> ");
SymbolListDump(stdout, BList, " ");
printf("\n");
nA = SymbolListCount(AList);
nB = SymbolListCount(BList);
ActionCount = 0;
FoundActions = FALSE;
LastSymbolMatched = FALSE;
A = B = NULL;
for(iA=iB=0; iA < nA || iB < nB; ++iA,++iB)
{
/* advance to next "real" symbol in AList (if any) */
for(A = NULL; iA < nA; ++iA)
{
A = SymbolListGet(AList, iA);
if(SymbolIsAction(A))
{
A = NULL;
++ActionCount;
}
else
break;
}
/* advance to next "real" symbol in BList (if any) */
for(B = NULL; iB < nB; ++iB)
{
B = SymbolListGet(BList, iB);
if(SymbolIsAction(B))
{
B = NULL;
++ActionCount;
}
else
break;
}
/* if there was another symbol in both productions */
if(A != NULL || B != NULL)
{
/* If both productions share another prefix symbol */
if(A == B)
{
LastSymbolMatched = TRUE;
if(ActionCount)
FoundActions = TRUE;
Common = SymbolListAdd(Common, A);
continue;
}
else
{
LastSymbolMatched = FALSE;
break;
}
}
/* else, we must have exhausted both lists */
assert(iA >= nA && iB >= nB);
}
MatchCount = SymbolListCount(Common);
if(LastSymbolMatched == TRUE)
{
fprintf(stderr, "Nonterminal '%s' has two or more rules with identical symbols:\n", SymbolStr(NonTerm));
SymbolListDump(stderr, Common, " ");
fprintf(stderr, "\n");
Exit(-1, ERROR_RULES_ARE_IDENTICAL);
}
/* */
else if(MatchCount > 0)
{
fprintf(stdout, " # of common left symbols=%d: ", SymbolListCount(Common));
SymbolListDump(stdout, Common, " ");
printf("\n");
if(FoundActions)
{
fprintf(stderr, "Nonterminal '%s': %s\n",
SymbolStr(NonTerm),
"two rules share a common prefix containing embedded actions\n");
fprintf(stderr, " -> ");
SymbolListDump(stderr, AList, " ");
fprintf(stderr, "\n");
fprintf(stderr, " -> ");
SymbolListDump(stderr, BList, " ");
fprintf(stderr, "\n");
Exit(-1, ERROR_COMMON_PREFIX_CONTAINS_ACTION);
}
}
SymbolListDestroy(Common);
fprintf(stderr, " LastSymbolMatched=%d, MatchCount=%d\n", LastSymbolMatched, MatchCount);
return MatchCount;
}
#endif
/* RuleItemCount() - return count of items, minus any trailing actions.
*
*/
int RuleItemCount(TRule* Rule)
{
int NSymbols;
SYMBOLS ProdItems = Rule->Symbols;
NSymbols = SymbolListCount(ProdItems);
if(NSymbols > 0 && SymbolIsAction(SymbolListGet(ProdItems, NSymbols-1)))
--NSymbols;
return NSymbols;
}
/* RuleFirst() - return FIRST set for suffix of production.
*
* Note that it is benign if iProdItem refers past the last
* production item; the result is simply an empty set.
*
* Note also that we must produce a correct result even if
* the rule contains direct left recursion. Suppose the rule
* looks like this:
* X -> X s1 s2 ... sn
*
*/
SYMBOLS RuleFirst(TSymbol* NonTerm, TRule* Rule, int iProdItem)
{
int DLR = FALSE; /* assume rule is not direct left recursion */
TSymbol* Symbol;
SYMBOLS First = NULL;
int NProdItems = SymbolListCount(Rule->Symbols);
NProdItems = SymbolListCount(Rule->Symbols);
if(NProdItems > 0)
if(SymbolIsAction(SymbolListGet(Rule->Symbols, NProdItems-1)))
--NProdItems;
if(SymbolListGet(Rule->Symbols, 0) == NonTerm)
DLR = TRUE;
for(; iProdItem < NProdItems; ++iProdItem)
{
Symbol = SymbolListGet(Rule->Symbols, iProdItem);
SymbolListAddList(&First, Symbol->First);
if(!Symbol->Nullable)
break;
}
#if 0
if(DLR && iProdItem >= NProdItems)
{
for(iProdItem=1; iProdItem < NProdItems; ++iProdItem)
{
Symbol = SymbolListGet(Rule->Symbols, iProdItem);
SymbolListAddList(&First, Symbol->First);
if(!Symbol->Nullable)
break;
}
}
#endif
return First;
}
/* RuleNullable() - is a suffix of a production nullable?
*
* If the caller set iProdItem past the end of the production
* list, then we claim "TRUE".
*/
int RuleNullable(TRule* Rule, int Position)
{
int NProdItems, iProdItem;
int Nullable = TRUE;
TSymbol* Symbol;
NProdItems = SymbolListCount(Rule->Symbols);
if(Position < NProdItems)
{
iProdItem = Position;
while((Symbol=SymbolListGet(Rule->Symbols, iProdItem)) != NULL && Symbol->Nullable)
++iProdItem;
if(iProdItem < NProdItems)
Nullable = FALSE;
}
if(Globals.Dump && Globals.Verbose > 1)
{
fprintf(stderr, "RuleNullable([%d]-> ", Position);
SymbolListDump(stderr, Rule->Symbols, " ");
fprintf(stderr, ") = %d\n", Nullable);
}
return Nullable;
}
/* RuleIsNull() - is this rule an epsilon production?
*
* Note that this is a test of whether the rule is empty
* or not, not a question of nullability.
*
*/
int RuleIsNull(TRule* Rule)
{
return Rule->Symbols == NULL || SymbolListCount(Rule->Symbols) == 0;
}
static
size_t Hash(const char* Name, size_t Len)
{
size_t Result = Len;
while(Len-- > 0)
Result = (Result << 5) ^ *Name++;
return Result % HASH_TABLE_SIZE;
}
TSymbol* SymbolFind(TToken Token)
{
TSymbol* Result = NULL;
size_t Index;
SYMBOLS Symbols;
Index = Hash(Token.Text, Token.TextLen);
Symbols = HashTable[Index];
if(Symbols != NULL)
Result = SymbolListFind(Symbols, Token);
return Result;
}
/* SymbolAdd() - add a new symbol to the global symbol table.
*
* This is the sole location where a new TSymbol structure is
* allocated.
*/
TSymbol* SymbolAdd(TToken Token, int Type)
{
TSymbol* Symbol;
size_t Index;
assert(Type == SYM_TERMINAL || Type == 0);
Index = Hash(Token.Text, Token.TextLen);
/* assert that no one has added this symbol before */
if(HashTable[Index])
{
SymIt Symbols = SymItNew(HashTable[Index]);
while(SymbolIterate(&Symbols))
if(Symbols.Symbol->Name.TextLen == Token.TextLen)
assert(strncmp(Symbols.Symbol->Name.Text, Token.Text, Token.TextLen));
}
Symbol = NEW(TSymbol);
assert(Symbol != NULL);
mwMark(Symbol, "NEW(TSymbol)", __FILE__, __LINE__);
Symbol->Name = Token;
if(Type)
SymbolSetBit(Symbol, Type);
HashTable[Index] = SymbolListAdd(HashTable[Index], Symbol);
return Symbol;
}
/* SymbolIsAction() - is this symbol just a dummy for an action?
*
* We create a dummy non-terminal for every action. This function
* returns TRUE if that's what kind of symbol this is.
*/
int SymbolIsAction(TSymbol* Symbol)
{
return Symbol->Action != NULL;
}
/* SymbolIsEmpty() - does this symbol derive anything at all?
*
* Returns TRUE if this symbol produces absolutely nothing. Since
* actions are stored as empty non-terminals, there will be a fair
* number of empty non-terminals even if the user declared none
* explicitly.
*
* Often, we need to treat actions differently from other non-terminals,
* but sometimes we can lump actions in with any other non-terminal that
* is empty (as in when searching for left recursion).
*/
int SymbolIsEmpty(TSymbol* Symbol)
{
return (Symbol->Bits & SYM_EMPTY) != 0;
}
int SymbolIsTerminal(TSymbol* Symbol)
{
return (Symbol->Bits & SYM_TERMINAL) != 0;
}
int SymbolIsNullable(TSymbol* A)
{
return A->Nullable;
}
int SymbolIsOpSyms(TSymbol* Symbol)
{
TRule** Rover;
// int iRule, NRules;
TRule* Rule;
TSymbol* OpSym;
Rover = Symbol->Rules;
if(Rover)
{
for(; *Rover; ++Rover)
{
Rule = *Rover;
if(SymbolListCount(Rule->Symbols) != 1)
return FALSE;
OpSym = SymbolListGet(Rule->Symbols, 0);
if(!OperatorFindOpSym(NULL, OpSym))
return FALSE;
}
}
return TRUE;
}
SYMBOLS SymbolGetAllSymbols(TSymbol* Symbol)
{
TRule** Rover;
TRule* Rule;
SYMBOLS List = NULL;
Rover = Symbol->Rules;
if(Rover)
for(; *Rover; ++Rover)
{
Rule = *Rover;
SymbolListAddList(&List, Rule->Symbols);
}
return List;
}
/* SymbolStart() - return the implicit start symbol.
*
*/
TSymbol* SymbolStart(void)
{
return StartSymbol;
}
/* SymbolAddStart() - add a new start symbol.
*
* Adding a start symbol consists of adding a new right-hand-side
* to the implicit start symbol that consists of the given symbol
* followed by the end symbol.
*/
TSymbol* SymbolAddStart(TSymbol* NewStart)
{
TRule* NewRule;
if(StartSymbol == NULL)
StartSymbol = SymbolNewNonTerm(StartToken);
assert(StartSymbol != NULL);
NewRule = SymbolNewRule(StartSymbol);
assert(NewStart != NULL);
NewRule->Symbols = SymbolListAdd(NewRule->Symbols, NewStart);
assert(EndSymbol != NULL);
NewRule->Symbols = SymbolListAdd(NewRule->Symbols, EndSymbol);
return StartSymbol;
}
int SymbolSetBit(TSymbol* Symbol, int Bit)
{
int Result = Symbol->Bits & ~Bit;
Symbol->Bits |= Bit;
return Result;
}
int SymbolGetBit(TSymbol* Symbol, int Bit)
{
return Symbol->Bits & Bit;
}
/* SymbolDupRule() - add a copy of a rule to an existing non-terminal
*/
TRule* SymbolDupRule(TSymbol* Symbol, TRule* OldRule)
{
int NewCount = RuleCount(Symbol) + 1;
TRule* NewRule = NEW(TRule);
assert(NewRule != NULL);
assert(Symbol != NULL);
assert(SymbolGetBit(Symbol, SYM_TERMINAL) == FALSE);
NewRule->Nullable = OldRule->Nullable;
NewRule->Predicate = OldRule->Predicate;
NewRule->Symbols = SymbolListCopy(NULL, OldRule->Symbols);
NewRule->First = SymbolListCopy(NULL, OldRule->First);
Symbol->Rules = (TRule**)realloc(Symbol->Rules, (NewCount+1)*sizeof(TRule*));
assert(Symbol->Rules != NULL);
Symbol->Rules[NewCount-1] = NewRule;
Symbol->Rules[NewCount] = NULL; /* null-terminate array of pointers */
return NewRule;
}
TRule* RuleDup(TRule* OldRule)
{
TRule* NewRule = NEW(TRule);
assert(NewRule != NULL);
NewRule->Nullable = OldRule->Nullable;
NewRule->Predicate = OldRule->Predicate;
NewRule->Symbols = SymbolListCopy(NULL, OldRule->Symbols);
return NewRule;
}
/* SymbolNewRule() - add a rule to an existing non-terminal
*/
TRule* SymbolNewRule(TSymbol* Symbol)
{
int NewCount = RuleCount(Symbol) + 1;
TRule* NewRule = NEW(TRule);
assert(NewRule != NULL);
assert(Symbol != NULL);
assert(SymbolGetBit(Symbol, SYM_TERMINAL) == FALSE);
Symbol->Rules = (TRule**)realloc(Symbol->Rules, (NewCount+1)*sizeof(TRule*));
assert(Symbol->Rules != NULL);
Symbol->Rules[NewCount-1] = NewRule;
Symbol->Rules[NewCount] = NULL; /* null-terminate array of pointers */
return NewRule;
}
TRule* SymbolAddRule(TSymbol* Symbol, TRule* NewRule)
{
int NewCount = RuleCount(Symbol) + 1;
assert(NewRule != NULL);
assert(Symbol != NULL);
assert(SymbolGetBit(Symbol, SYM_TERMINAL) == FALSE);
Symbol->Rules = (TRule**)realloc(Symbol->Rules, (NewCount+1)*sizeof(TRule*));
assert(Symbol->Rules != NULL);
Symbol->Rules[NewCount-1] = NewRule;
Symbol->Rules[NewCount] = NULL; /* null-terminate array of pointers */
return NewRule;
}
TToken Unquote(TToken Token)
{
if(Token.TextLen > 2 && Token.Text[0] == '\'' && Token.Text[Token.TextLen-1] == '\'')
{
++Token.Text;
Token.TextLen -= 2;
}
return Token;
}
TSymbol* LiteralFind(TToken Token)
{
TSymbol* Result = NULL;
int iLiteral;
Token = Unquote(Token);
for(iLiteral = 0; iLiteral < NLiterals; ++iLiteral)
if(TokenEqual(Token, Literals[iLiteral].Literal))
{
Result = Literals[iLiteral].Terminal;
break;
}
return Result;
}
TToken LiteralFromSymbol(TSymbol* Symbol)
{
TToken Result = { 0 };
int iLiteral;
for(iLiteral = 0; iLiteral < NLiterals; ++iLiteral)
if(Literals[iLiteral].Terminal == Symbol)
{
Result = Literals[iLiteral].Literal;
break;
}
return Result;
}
/* LiteralAdd() - associate a literal with a symbol.
*
* We assume the caller will use LiteralFind() to avoid adding
* the same literal twice, or associating the same literal with
* more than one symbol.
*/
void LiteralAdd(TSymbol* Symbol, TToken Token)
{
++NLiterals;
Literals = realloc(Literals, sizeof(TLiteral)*NLiterals);
assert(Literals != NULL);
Token = Unquote(Token);
Literals[NLiterals-1].Terminal = Symbol;
Literals[NLiterals-1].Literal = Token;
}
/*******************
* Rule functions *
*******************/
void RuleAddSymbol(TRule* Rule, TSymbol* Symbol, TToken Token)
{
int NSymbols;
Rule->Symbols = SymbolListAdd(Rule->Symbols, Symbol);
NSymbols = SymbolListCount(Rule->Symbols);
Rule->Tokens = (TToken *)realloc((void*)Rule->Tokens, sizeof(TToken)*NSymbols);
Rule->Tokens[NSymbols-1] = Token;
}
TSymbol* RuleRemoveSymbol(TRule* Rule, int Pos)
{
int NSymbols, iToken;
TSymbol* Result = NULL;
SYMBOLS Symbols;
Symbols = Rule->Symbols;
NSymbols = SymbolListCount(Symbols);
if(Pos < NSymbols)
{
Result = SymbolListDelete(Symbols, Pos);
/* might be no tokens if, for example, rule was victim of
* a left-corner transformation.
*/
if(Rule->Tokens)
for(iToken = Pos; iToken < NSymbols-1; ++iToken)
Rule->Tokens[iToken] = Rule->Tokens[iToken+1];
}
return Result;
}
/* these come last, so I can safely undef their macro
* aliases.
*/
#undef SymbolListCreate
SYMBOLS SymbolListCreate(void)
{
return (SYMBOLS)NEW(TList);
}
#undef SymbolListDestroy
SYMBOLS SymbolListDestroy(SYMBOLS Handle)
{
TList* List = (TList*)Handle;
if(List)
{
if(List->Symbols)
free(List->Symbols);
free(List);
}
return NULL;
}
/* SymbolListAdd() - add new symbol to a list (duh)
*
* Note that it is OK to pass in a NULL pointer for the symbol
* that is being added. We use NULL pointers as placeholders for
* operands in the symbol lists that describe operators.
*/
#undef SymbolListAdd
SYMBOLS SymbolListAdd(SYMBOLS Handle, TSymbol* Symbol)
{
TList* List;
if(Handle == NULL)
Handle = SymbolListCreate();
List = (TList*)Handle;
++List->NSymbols;
List->Symbols = realloc(List->Symbols, sizeof(TSymbol*) * List->NSymbols);
assert(List->Symbols != NULL);
List->Symbols[List->NSymbols-1] = Symbol;
return Handle;
}
|
100siddhartha-blacc
|
symtab.c
|
C
|
mit
| 42,280
|
#ifndef COMMON_H_
#define COMMON_H_
/* common.h - header file with information most files need.
*
* This should be included first by every .h and .c file. That ensures
* an opportunity to make early tweaks, such as is needed by Microsoft C++
* for memory debugging.
*/
//#include "microsoft.h" // should be first include in this file.
#include <cassert>
#include <cstdarg>
#include <string>
#include <cstring>
#include <memory>
using std::unique_ptr;
// define some annotations
#if defined(_MSC_VER)
# define A_NORETURN __declspec(noreturn)
#elif defined(__GNUC__)
# define A_NORETURN __attribute__((noreturn))
#else
# define A_NORETURN
#endif
#ifdef _MSC_VER
// if we let him check realloc, he'll make innumerable spurious complaints...
inline _Check_return_ void* r_i_p(void* ptr, size_t NewSize)
{
void* Result = realloc(ptr, NewSize);
__analysis_assume(Result != NULL);
return Result;
}
#else
# define __analysis_assume
# define r_i_p realloc
#endif
class Global
{
private:
static struct OptionBag // options we might need two copies of
{
int ExpectCode;
int ExpectLine;
int TabStop;
bool DumpFlag;
bool VerboseFlag;
bool TokenizeFlag;
const char* ShowFirst;
const char* ShowFollow;
const char* StyleFile;
const char* InputFile;
} Options;
static int GetIntArg(int Char, const char* Arg);
public:
static void ParseArgs(int ArgCount, char** Args, Global::OptionBag* Options=NULL);
friend void A_NORETURN Exit(int Line, int Error);
static int Dump() { return Options.DumpFlag; }
static int Verbose() { return Options.VerboseFlag; }
static int Tokenize() { return Options.TokenizeFlag; }
static const char* InputFilename() { return Options.InputFile; }
};
void A_NORETURN ErrorExit(int Code, const char* Format, ...);
void ErrorPrologue(int Code);
void Usage(const char* Format, ...);
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define ARGUNUSED(x) (void)(x)
#define MAX_OPERATOR_PATTERN (32)
enum ERRORCODE
{
ERROR_NONE = 0,
ERROR_COMMANDLINE = 1, /* error on commandline */
ERROR_TERM_USED_AS_NONTERM = 2, /* */
ERROR_UNDECL_LITERAL_IN_PROD = 3,
ERROR_MISSING_NAME_IN_TOKEN_DECL = 4,
ERROR_LITERAL_ALREADY_DEFINED = 5,
ERROR_UNDEFINED_OPERATOR = 6,
ERROR_EOF_IN_PREC = 7,
ERROR_EXPECTING_OPERATOR_DECL = 8,
ERROR_PREC_WITHOUT_OPERATORS = 9,
ERROR_BAD_TOKEN_IN_DECL = 10,
ERROR_EXPECTING_NONTERM = 11,
ERROR_EXPECTING_COLON = 12,
ERROR_EXPECTING_AFTER_ACTION = 13,
ERROR_EXPECTING_OR_SEMI = 14,
ERROR_CANT_OPEN_INPUT_FILE = 15,
ERROR_INPUT_FILE_TOO_BIG = 16,
ERROR_UNKNOWN_FREAD_ERROR = 17,
ERROR_FREAD_FELL_SHORT = 18,
ERROR_UNDEFINED_NONTERM = 19,
ERROR_EOF_IN_COMMENT = 20,
ERROR_TERM_ALREADY_DEFINED = 21,
ERROR_EXPECTING_SEMICOLON = 22,
ERROR_LL_CONFLICT = 23,
ERROR_UNREACHABLE_NONTERMINAL = 24,
ERROR_UNDECL_LITERAL_IN_OP_DECL = 25,
ERROR_DUPL_OP_DECL = 26,
ERROR_OP_DECL_TOO_LONG = 27,
ERROR_DUP_SYM_IN_OPERATOR = 28,
ERROR_FAILED_OP_PREC_TABLE = 29,
ERROR_PREFIX_UNARY_DECL_LEFT = 30,
ERROR_POSTFIX_UNARY_DECL_RIGHT = 31,
ERROR_EOF_IN_TEST = 32,
ERROR_UNDEF_SYMBOL_IN_TEST = 33,
ERROR_NONTERM_IN_TEST = 34,
ERROR_BAD_TOKEN_IN_TEST = 35,
ERROR_LEFT_RECURSION = 36,
ERROR_BAD_NAME_IN_TEMPLATE = 37,
ERROR_EXPECTING_IDENT_AFTER_START = 38,
ERROR_RULES_ARE_IDENTICAL = 39,
ERROR_COMMON_PREFIX_CONTAINS_ACTION = 40,
ERROR_SYMBOL_DOES_NOT_TERMINATE = 41,
ERROR_A_NULLABLE_B_CLASH = 42,
ERROR_TWO_NULLABLE_RULES = 43,
ERROR_ILLEGAL_TOKEN = 44,
ERROR_BAD_QUOTE = 45,
ERROR_REDUCE_REDUCE_CONFLICT = 46,
ERROR_MUST_BE_NONASSOC = 47,
ERROR_NO_SYMBOL_BEFORE_SLASH = 48,
ERROR_NO_EMBEDDED_ACTION = 49,
ERROR_NOT_OPERATOR_OR_OPERAND = 50,
ERROR_NO_MATCHING_OPERATOR_PATTERN = 51,
ERROR_MISSING_OPERAND_IN_DECL = 52,
ERROR_BAD_OP_ABBREV = 53,
ERROR_CLASH_IN_OP_ABBREV = 54,
ERROR_SUFFIXES_NULLABLE = 55,
ERROR_SUFFIXES_CLASH = 56,
};
void ExitExpect(int LineNumber, int ErrorNumber);
//void A_NORETURN Exit(int LineNumber, int ErrorNumber);
void ErrorPrologue(int Error);
void A_NORETURN ErrorExit(int Error, const char* Format, ...);
void A_NORETURN Error(const char* Format, ...);
void ErrorEpilog(int Line);
void Dump(const char* Format, ...);
void DumpVerbose(const char* Format, ...);
void Usage(const char* Format, ...);
//char* StrClone(const char* Src);
//int StrEndsWith(const char* Src, const char* Suffix);
//#define NEW(T) ((T*)calloc(1, sizeof(T)))
#define ISALPHA(x) isalpha((unsigned char)(x))
#define ISDIGIT(x) isdigit((unsigned char)(x))
#endif
|
100siddhartha-blacc
|
common.h
|
C++
|
mit
| 5,830
|
/* cstr.c - Utility to transform text file into compilable C array of char.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define TRUE (1)
#define FALSE (0)
void Usage()
{
fprintf(stderr, "Usage: cstr filename.str\n");
exit(EXIT_FAILURE);
}
void GetTarget(const char* Input, char* Output)
{
const char* InFile = Input;
char* LastDot = NULL;
while((*Output=*InFile++) != '\0')
{
if(*Output == '.')
LastDot = Output;
++Output;
}
if(LastDot == NULL || strcmp(LastDot, ".str"))
{
fprintf(stderr, "'%s' does not end in '.str'\n", Input);
Usage();
}
strcpy(LastDot, ".c");
}
int LegalChar(char c)
{
return isalnum(c) || (c == '_');
}
int ParseLine(const char* Input, char* ArrayName, int* ArraySize)
{
int Result = FALSE;
if(isalpha(*Input) || *Input == '_')
{
while(LegalChar(*Input))
*ArrayName++ = *Input++;
*ArrayName = '\0';
/* got array name, now skip over white space */
while(*Input && isspace(*Input))
++Input;
/* now see if array size was specified */
if(isdigit(*Input))
*ArraySize = atoi(Input);
Result = TRUE;
}
return Result;
}
char* AddChar(char* Rover, char C)
{
if(isgraph(C) && C != '\\' && C != '\'')
*Rover++ = C;
else if(C == ' ')
*Rover++ = C;
else
{
*Rover++ = '\\';
switch(C)
{
case '\\' : *Rover++ = '\\'; break;
case '\b' : *Rover++ = 'b'; break;
case '\f' : *Rover++ = 'f'; break;
case '\r' : *Rover++ = 'r'; break;
case '\n' : *Rover++ = 'n'; break;
case '\t' : *Rover++ = 't'; break;
case '\0' : *Rover++ = '0'; break;
case '\'' : *Rover++ = '\''; break;
default :
sprintf(Rover, "x%02X", C&0x00FF);
Rover += 3;
}
}
return Rover;
}
void cstr(FILE* Input, FILE* Output, const char* ArrayName, int ArraySize)
{
int Column = 0;
int C;
int Eof;
fprintf(Output, "/* machine generated -- do not edit! */\n");
fprintf(Output, "char %s[", ArrayName);
if(ArraySize > 0)
fprintf(Output, "%d", ArraySize);
fprintf(Output, "] =\n");
fprintf(Output, " {\n");
// while((C = fgetc(Input)) != EOF)
for(Eof=FALSE; !Eof;)
{
char Buffer[16];
char* Rover = Buffer;
C = fgetc(Input);
if(C == EOF)
{
Eof = TRUE;
C = '\0';
}
*Rover++ = '\'';
Rover = AddChar(Rover, (char)C);
*Rover++ = '\'';
*Rover++ = '\0';
if(Column >= 68)
{
fprintf(Output, ",\n");
Column = 0;
}
if(Column == 0)
{
fprintf(Output, " ");
}
else
{
fprintf(Output, ",");
while(++Column % 8)
fprintf(Output, " ");
}
fprintf(Output, "%s", Buffer);
Column += strlen(Buffer)+1;
}
fprintf(Output, "\n };\n");
}
int main(int argc, char**argv)
{
char Target[1024];
char Line[1024];
char ArrayName[1024];
int ArraySize = -1;
FILE* Input;
FILE* Output;
if(argc != 2)
Usage();
Input = fopen(argv[1], "r");
if(Input == NULL)
{
fprintf(stderr, "Can't open '%s' for reading!\n", argv[1]);
Usage();
}
if( !fgets(Line, sizeof(Line), Input)
|| !ParseLine(Line, ArrayName, &ArraySize)
)
{
fprintf(stderr, "First line in file should be of format: array_name [array_size]\n");
Usage();
}
GetTarget(argv[1], Target);
fprintf(stderr, "Target is %s, array '%s'[%d]\n", Target, ArrayName, ArraySize);
Output = fopen(Target, "w");
if(Output == NULL)
{
fprintf(stderr, "Unable to open '%s' for writing.\n", Target);
exit(EXIT_FAILURE);
}
cstr(Input, Output, ArrayName, ArraySize);
exit(EXIT_SUCCESS);
}
|
100siddhartha-blacc
|
cstr.c
|
C
|
mit
| 4,749
|
#ifndef CHECK_H_
#define CHECK_H_
#ifndef SYMTAB_H_
#include "symtab.h"
#endif
int CheckCompleteness(void);
int CheckCircularity(void);
void CheckReachability(void);
int CheckTermination(void);
void CheckOpsUsed(void);
void CheckLeftRecursion(void);
void CheckFirstFollowClash(void);
void CheckFirstFirstClash(void);
void CheckLR0Rules(void);
int CommonLeft(TSymbol* NonTerm, SYMBOLS AList, SYMBOLS BList);
#endif /* CHECK_H_ */
|
100siddhartha-blacc
|
check.h
|
C
|
mit
| 487
|
#ifndef GEN_C_H_
#define GEN_C_H_
#include "generate.h"
int GenerateC(FILE* Output, TParseTables* Tables);
#endif /* GEN_C_H_ */
|
100siddhartha-blacc
|
gen_c.h
|
C
|
mit
| 144
|
#ifdef _MSC_VER
#include "common.h"
void MicrosoftDebug()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF /*| _CRTDBG_CHECK_CRT_DF */);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
}
#endif
|
100siddhartha-blacc
|
microsoft.cpp
|
C++
|
mit
| 528
|
#ifndef LOADFILE_H_
#define LOADFILE_H_
char* LoadFile(const char* Filename);
#endif /* LOADFILE_H_ */
|
100siddhartha-blacc
|
loadfile.h
|
C
|
mit
| 113
|
#ifndef SYMLIST_H_
#define SYMLIST_H_
#ifndef SYMBOL_H_
# include "symbol.h"
#endif
typedef struct SYMLIST_
{
void* Dummy_;
} SYMLIST_, *SYMLIST;
SYMLIST SymListCreate(void);
//#ifdef MEMWATCH
//# define SymListCreate() (SYMLIST)mwMark((void*)SymListCreate(), "symbol list", __FILE__, __LINE__)
//#endif
SYMLIST SymListDestroy(SYMLIST List);
//#ifdef MEMWATCH
//# define SymListDestroy(List) ((List)?(mwUnmark(List, __FILE__, __LINE__),SymListDestroy(List)):NULL)
//#endif
SYMLIST SymListAdd(SYMLIST List, SYMBOL Symbol);
//#ifdef MEMWATCH
#if 0
# define SymListAdd(List, Symbol) List?SymListAdd(List,Symbol):(SYMLIST)mwMark(SymListAdd(List,Symbol), "SymListAdd", __FILE__, __LINE__);
#endif
SYMLIST SymListAddFirst(SYMLIST List, SYMBOL ProdItem);
int SymListAddList(SYMLIST* List, SYMLIST Add);
SYMLIST SymListAddUnique(SYMLIST Handle, SYMBOL Symbol);
int SymListCount(SYMLIST List);
int SymListCountSig(SYMLIST List);
SYMLIST SymListCopy(SYMLIST To, SYMLIST From);
SYMBOL SymListGet(SYMLIST List, int Index);
int SymListEqual(SYMLIST A, SYMLIST B);
SYMBOL SymListFind(SYMLIST List, TToken Token);
int SymListIndex(SYMLIST List, SYMBOL Symbol);
int SymListRemove(SYMLIST List, SYMBOL Symbol);
SYMLIST SymListTruncate(SYMLIST List, int NewLen);
SYMBOL SymListDelete(SYMLIST List, int Position);
int SymListContains(SYMLIST List, SYMBOL Symbol);
SYMLIST SymListIntersect(SYMLIST List, SYMLIST With);
int SymListDump(FILE* Handle, SYMLIST List, const char* Sep);
char* SymListDumpStr(SYMLIST List, const char* Sep);
#define SymListPush SymListAdd
/* void SymListPush(SYMLIST List, SYMBOL Symbol);*/
SYMBOL SymListPop(SYMLIST List);
SYMBOL SymListTop(SYMLIST List);
SYMLIST SymListReplace(SYMLIST List, int Pos, SYMLIST Insert);
#endif
|
100siddhartha-blacc
|
symlist.h
|
C
|
mit
| 1,972
|
#ifndef LR0_H_
#define LR0_H_
/* lr0.h - interface to LR(0) code.
*/
#include <limits.h>
#if UINT_MAX < (0xFFFFFFFF)
typedef int TITEM;
#else
typedef long TITEM;
#endif
#include "symtab.h"
typedef struct TItemSet
{
int Count;
TITEM* Items;
} TItemSet;
typedef struct TTransition
{
TSymbol* Symbol;
int NextState;
} TTransition;
typedef struct TTransitions
{
int Count;
TTransition*Transitions;
} TTransitions;
typedef struct TState
{
int Final;
int Accepting;
int Inbound;
TItemSet ItemSet;
TTransitions Transitions;
} TState;
typedef struct TStates
{
int Start; /* index in States of start state */
int Count;
TState** States;
SYMBOLS OpTokens; /* list of operator tokens used by state machine */
int TokenClassCount;
SYMBOLS* TokenClasses;
} TStates;
#if 0
int ItemAdd(TItemSet* Set, int Rule, int Position);
int ItemSetCmp(TItemSet* A, TItemSet* B);
TStates* StatesNew(void);
TState* StateNew(void);
#endif
void ComputeAllLR0(void);
#endif /* LR0_H_ */
|
100siddhartha-blacc
|
lr0.h
|
C
|
mit
| 1,363
|
#ifndef GLOBALS_H_
#define GLOBALS_H_
/* globals.h - define our global variables.
*/
#ifndef SYMTAB_H_
#include "symlist.h"
#endif
typedef struct GLOBALS
{
int Verbose; /* user wants verbose output? */
int Dump; /* wants debugging output? */
SYMLIST NonTerms; /* list of all non-terminals */
SYMLIST Terminals; /* list of all terminals */
SYMLIST Actions; /* list of non-terminals that are actions */
INPUT Input;
int TabStop;
const char* InputFile;
const char* StyleFile;
TToken ProgramSection;
} GLOBALS;
extern GLOBALS Globals; /* defined in main.c */
#endif /* GLOBALS_H_ */
|
100siddhartha-blacc
|
globals.h
|
C
|
mit
| 808
|
/*
** MEMWATCH.C
** Nonintrusive ANSI C memory leak / overwrite detection
** Copyright (C) 1992-2003 Johan Lindh
** All rights reserved.
** Version 2.71
This file is part of MEMWATCH.
MEMWATCH 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.
MEMWATCH 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 MEMWATCH; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**
** 920810 JLI [1.00]
** 920830 JLI [1.10 double-free detection]
** 920912 JLI [1.15 mwPuts, mwGrab/Drop, mwLimit]
** 921022 JLI [1.20 ASSERT and VERIFY]
** 921105 JLI [1.30 C++ support and TRACE]
** 921116 JLI [1.40 mwSetOutFunc]
** 930215 JLI [1.50 modified ASSERT/VERIFY]
** 930327 JLI [1.51 better auto-init & PC-lint support]
** 930506 JLI [1.55 MemWatch class, improved C++ support]
** 930507 JLI [1.60 mwTest & CHECK()]
** 930809 JLI [1.65 Abort/Retry/Ignore]
** 930820 JLI [1.70 data dump when unfreed]
** 931016 JLI [1.72 modified C++ new/delete handling]
** 931108 JLI [1.77 mwSetAssertAction() & some small changes]
** 940110 JLI [1.80 no-mans-land alloc/checking]
** 940328 JLI [2.00 version 2.0 rewrite]
** Improved NML (no-mans-land) support.
** Improved performance (especially for free()ing!).
** Support for 'read-only' buffers (checksums)
** ^^ NOTE: I never did this... maybe I should?
** FBI (free'd block info) tagged before freed blocks
** Exporting of the mwCounter variable
** mwBreakOut() localizes debugger support
** Allocation statistics (global, per-module, per-line)
** Self-repair ability with relinking
** 950913 JLI [2.10 improved garbage handling]
** 951201 JLI [2.11 improved auto-free in emergencies]
** 960125 JLI [X.01 implemented auto-checking using mwAutoCheck()]
** 960514 JLI [2.12 undefining of existing macros]
** 960515 JLI [2.13 possibility to use default new() & delete()]
** 960516 JLI [2.20 suppression of file flushing on unfreed msgs]
** 960516 JLI [2.21 better support for using MEMWATCH with DLL's]
** 960710 JLI [X.02 multiple logs and mwFlushNow()]
** 960801 JLI [2.22 merged X.01 version with current]
** 960805 JLI [2.30 mwIsXXXXAddr() to avoid unneeded GP's]
** 960805 JLI [2.31 merged X.02 version with current]
** 961002 JLI [2.32 support for realloc() + fixed STDERR bug]
** 961222 JLI [2.40 added mwMark() & mwUnmark()]
** 970101 JLI [2.41 added over/underflow checking after failed ASSERT/VERIFY]
** 970113 JLI [2.42 added support for PC-Lint 7.00g]
** 970207 JLI [2.43 added support for strdup()]
** 970209 JLI [2.44 changed default filename to lowercase]
** 970405 JLI [2.45 fixed bug related with atexit() and some C++ compilers]
** 970723 JLI [2.46 added MW_ARI_NULLREAD flag]
** 970813 JLI [2.47 stabilized marker handling]
** 980317 JLI [2.48 ripped out C++ support; wasn't working good anyway]
** 980318 JLI [2.50 improved self-repair facilities & SIGSEGV support]
** 980417 JLI [2.51 more checks for invalid addresses]
** 980512 JLI [2.52 moved MW_ARI_NULLREAD to occur before aborting]
** 990112 JLI [2.53 added check for empty heap to mwIsOwned]
** 990217 JLI [2.55 improved the emergency repairs diagnostics and NML]
** 990224 JLI [2.56 changed ordering of members in structures]
** 990303 JLI [2.57 first maybe-fixit-for-hpux test]
** 990516 JLI [2.58 added 'static' to the definition of mwAutoInit]
** 990517 JLI [2.59 fixed some high-sensitivity warnings]
** 990610 JLI [2.60 fixed some more high-sensitivity warnings]
** 990715 JLI [2.61 changed TRACE/ASSERT/VERIFY macro names]
** 991001 JLI [2.62 added CHECK_BUFFER() and mwTestBuffer()]
** 991007 JLI [2.63 first shot at a 64-bit compatible version]
** 991009 JLI [2.64 undef's strdup() if defined, mwStrdup made const]
** 000704 JLI [2.65 added some more detection for 64-bits]
** 010502 JLI [2.66 incorporated some user fixes]
** [mwRelink() could print out garbage pointer (thanks mac@phobos.ca)]
** [added array destructor for C++ (thanks rdasilva@connecttel.com)]
** [added mutex support (thanks rdasilva@connecttel.com)]
** 010531 JLI [2.67 fix: mwMutexXXX() was declared even if MW_HAVE_MUTEX was not defined]
** 010619 JLI [2.68 fix: mwRealloc() could leave the mutex locked]
** 020918 JLI [2.69 changed to GPL, added C++ array allocation by Howard Cohen]
** 030212 JLI [2.70 mwMalloc() bug for very large allocations (4GB on 32bits)]
** 030520 JLI [2.71 added ULONG_LONG_MAX as a 64-bit detector (thanks Sami Salonen)]
*/
#define __MEMWATCH_C 1
#ifdef MW_NOCPP
#define MEMWATCH_NOCPP
#endif
#ifdef MW_STDIO
#define MEMWATCH_STDIO
#endif
/***********************************************************************
** Include files
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <signal.h>
#include <setjmp.h>
#include <time.h>
#include <limits.h>
#include "memwatch.h"
#ifndef toupper
#include <ctype.h>
#endif
#if defined(WIN32) || defined(__WIN32__)
#define MW_HAVE_MUTEX 1
#include <windows.h>
#endif
#if defined(MW_PTHREADS) || defined(HAVE_PTHREAD_H)
#define MW_HAVE_MUTEX 1
#include <pthread.h>
#endif
/***********************************************************************
** Defines & other weird stuff
***********************************************************************/
/*lint -save -e767 */
#define VERSION "2.71" /* the current version number */
#define CHKVAL(mw) (0xFE0180L^(long)mw->count^(long)mw->size^(long)mw->line)
#define FLUSH() mwFlush()
#define TESTS(f,l) if(mwTestAlways) (void)mwTestNow(f,l,1)
#define PRECHK 0x01234567L
#define POSTCHK 0x76543210L
#define mwBUFFER_TO_MW(p) ( (mwData*) (void*) ( ((char*)p)-mwDataSize-mwOverflowZoneSize ) )
/*lint -restore */
#define MW_NML 0x0001
#ifdef _MSC_VER
#define COMMIT "c" /* Microsoft C requires the 'c' to perform as desired */
#else
#define COMMIT "" /* Normal ANSI */
#endif /* _MSC_VER */
#ifdef __cplusplus
#define CPPTEXT "++"
#else
#define CPPTEXT ""
#endif /* __cplusplus */
#ifdef MEMWATCH_STDIO
#define mwSTDERR stderr
#else
#define mwSTDERR mwLog
#endif
#ifdef MW_HAVE_MUTEX
#define MW_MUTEX_INIT() mwMutexInit()
#define MW_MUTEX_TERM() mwMutexTerm()
#define MW_MUTEX_LOCK() mwMutexLock()
#define MW_MUTEX_UNLOCK() mwMutexUnlock()
#else
#define MW_MUTEX_INIT()
#define MW_MUTEX_TERM()
#define MW_MUTEX_LOCK()
#define MW_MUTEX_UNLOCK()
#endif
/***********************************************************************
** If you really, really know what you're doing,
** you can predefine these things yourself.
***********************************************************************/
#ifndef mwBYTE_DEFINED
# if CHAR_BIT != 8
# error need CHAR_BIT to be 8!
# else
typedef unsigned char mwBYTE;
# define mwBYTE_DEFINED 1
# endif
#endif
#if defined(ULONGLONG_MAX) || defined(ULLONG_MAX) || defined(_UI64_MAX) || defined(ULONG_LONG_MAX)
# define mw64BIT 1
# define mwROUNDALLOC_DEFAULT 8
#else
# if UINT_MAX <= 0xFFFFUL
# define mw16BIT 1
# define mwROUNDALLOC_DEFAULT 2
# else
# if ULONG_MAX > 0xFFFFFFFFUL
# define mw64BIT 1
# define mwROUNDALLOC_DEFAULT 8
# else
# define mw32BIT 1
# define mwROUNDALLOC_DEFAULT 4
# endif
# endif
#endif
/* mwROUNDALLOC is the number of bytes to */
/* round up to, to ensure that the end of */
/* the buffer is suitable for storage of */
/* any kind of object */
#ifndef mwROUNDALLOC
# define mwROUNDALLOC mwROUNDALLOC_DEFAULT
#endif
#ifndef mwDWORD_DEFINED
#if ULONG_MAX == 0xFFFFFFFFUL
typedef unsigned long mwDWORD;
#define mwDWORD_DEFINED "unsigned long"
#endif
#endif
#ifndef mwDWORD_DEFINED
#if UINT_MAX == 0xFFFFFFFFUL
typedef unsigned int mwDWORD;
#define mwDWORD_DEFINED "unsigned int"
#endif
#endif
#ifndef mwDWORD_DEFINED
#if USHRT_MAX == 0xFFFFFFFFUL
typedef unsigned short mwDWORD;
#define mwDWORD_DEFINED "unsigned short"
#endif
#endif
#ifndef mwBYTE_DEFINED
#error "can't find out the correct type for a 8 bit scalar"
#endif
#ifndef mwDWORD_DEFINED
#error "can't find out the correct type for a 32 bit scalar"
#endif
/***********************************************************************
** Typedefs & structures
***********************************************************************/
/* main data holding area, precedes actual allocation */
typedef struct mwData_ mwData;
struct mwData_ {
mwData* prev; /* previous allocation in chain */
mwData* next; /* next allocation in chain */
const char* file; /* file name where allocated */
long count; /* action count */
long check; /* integrity check value */
#if 0
long crc; /* data crc value */
#endif
size_t size; /* size of allocation */
int line; /* line number where allocated */
unsigned flag; /* flag word */
};
/* statistics structure */
typedef struct mwStat_ mwStat;
struct mwStat_ {
mwStat* next; /* next statistic buffer */
const char* file;
long total; /* total bytes allocated */
long num; /* total number of allocations */
long max; /* max allocated at one time */
long curr; /* current allocations */
int line;
};
/* grabbing structure, 1K in size */
typedef struct mwGrabData_ mwGrabData;
struct mwGrabData_ {
mwGrabData* next;
int type;
char blob[ 1024 - sizeof(mwGrabData*) - sizeof(int) ];
};
typedef struct mwMarker_ mwMarker;
struct mwMarker_ {
void *host;
char *text;
mwMarker *next;
int level;
};
#if defined(WIN32) || defined(__WIN32__)
typedef HANDLE mwMutex;
#endif
#if defined(MW_PTHREADS) || defined(HAVE_PTHREAD_H)
typedef pthread_mutex_t mwMutex;
#endif
/***********************************************************************
** Static variables
***********************************************************************/
static int mwInited = 0;
static int mwInfoWritten = 0;
static int mwUseAtexit = 0;
static FILE* mwLog = NULL;
static int mwFlushing = 0;
static int mwStatLevel = MW_STAT_DEFAULT;
static int mwNML = MW_NML_DEFAULT;
static int mwFBI = 0;
static long mwAllocLimit = 0L;
static int mwUseLimit = 0;
static long mwNumCurAlloc = 0L;
static mwData* mwHead = NULL;
static mwData* mwTail = NULL;
static int mwDataSize = 0;
static unsigned char mwOverflowZoneTemplate[] = "mEmwAtch";
static int mwOverflowZoneSize = mwROUNDALLOC;
static void (*mwOutFunction)(int) = NULL;
static int (*mwAriFunction)(const char*) = NULL;
static int mwAriAction = MW_ARI_ABORT;
static char mwPrintBuf[MW_TRACE_BUFFER+8];
static unsigned long mwCounter = 0L;
static long mwErrors = 0L;
static int mwTestFlags = 0;
static int mwTestAlways = 0;
static FILE* mwLogB1 = NULL;
static int mwFlushingB1 = 0;
static mwStat* mwStatList = NULL;
static long mwStatTotAlloc = 0L;
static long mwStatMaxAlloc = 0L;
static long mwStatNumAlloc = 0L;
static long mwStatCurAlloc = 0L;
static long mwNmlNumAlloc = 0L;
static long mwNmlCurAlloc = 0L;
static mwGrabData* mwGrabList = NULL;
static long mwGrabSize = 0L;
static void * mwLastFree[MW_FREE_LIST];
static const char *mwLFfile[MW_FREE_LIST];
static int mwLFline[MW_FREE_LIST];
static int mwLFcur = 0;
static mwMarker* mwFirstMark = NULL;
static FILE* mwLogB2 = NULL;
static int mwFlushingB2 = 0;
#ifdef MW_HAVE_MUTEX
static mwMutex mwGlobalMutex;
#endif
/***********************************************************************
** Static function declarations
***********************************************************************/
static void mwAutoInit( void );
static FILE* mwLogR( void );
static void mwLogW( FILE* );
static int mwFlushR( void );
static void mwFlushW( int );
static void mwFlush( void );
static void mwIncErr( void );
static void mwUnlink( mwData*, const char* file, int line );
static int mwRelink( mwData*, const char* file, int line );
static int mwIsHeapOK( mwData *mw );
static int mwIsOwned( mwData* mw, const char* file, int line );
static int mwTestBuf( mwData* mw, const char* file, int line );
static void mwDefaultOutFunc( int );
static void mwWrite( const char* format, ... );
static void mwLogFile( const char* name );
static size_t mwFreeUp( size_t, int );
static const void *mwTestMem( const void *, unsigned, int );
static int mwStrCmpI( const char *s1, const char *s2 );
static int mwTestNow( const char *file, int line, int always_invoked );
static void mwDropAll( void );
static const char *mwGrabType( int type );
static unsigned mwGrab_( unsigned kb, int type, int silent );
static unsigned mwDrop_( unsigned kb, int type, int silent );
static int mwARI( const char* text );
static void mwStatReport( void );
static mwStat* mwStatGet( const char*, int, int );
static void mwStatAlloc( size_t, const char*, int );
static void mwStatFree( size_t, const char*, int );
static int mwCheckOF( const void * p );
static void mwWriteOF( void * p );
static char mwDummy( char c );
#ifdef MW_HAVE_MUTEX
static void mwMutexInit( void );
static void mwMutexTerm( void );
static void mwMutexLock( void );
static void mwMutexUnlock( void );
#endif
/***********************************************************************
** System functions
***********************************************************************/
void mwInit( void ) {
time_t tid;
if( mwInited++ > 0 ) return;
MW_MUTEX_INIT();
/* start a log if none is running */
if( mwLogR() == NULL ) mwLogFile( "memwatch.log" );
if( mwLogR() == NULL ) {
int i;
char buf[32];
/* oops, could not open it! */
/* probably because it's already open */
/* so we try some other names */
for( i=1; i<100; i++ ) {
sprintf( buf, "memwat%02d.log", i );
mwLogFile( buf );
if( mwLogR() != NULL ) break;
}
}
/* initialize the statistics */
mwStatList = NULL;
mwStatTotAlloc = 0L;
mwStatCurAlloc = 0L;
mwStatMaxAlloc = 0L;
mwStatNumAlloc = 0L;
mwNmlCurAlloc = 0L;
mwNmlNumAlloc = 0L;
/* calculate the buffer size to use for a mwData */
mwDataSize = sizeof(mwData);
while( mwDataSize % mwROUNDALLOC ) mwDataSize ++;
/* write informational header if needed */
if( !mwInfoWritten ) {
mwInfoWritten = 1;
(void) time( &tid );
mwWrite(
"\n============="
" MEMWATCH " VERSION " Copyright (C) 1992-1999 Johan Lindh "
"=============\n");
mwWrite( "\nStarted at %s\n", ctime( &tid ) );
/**************************************************************** Generic */
mwWrite( "Modes: " );
#ifdef mwNew
mwWrite( "C++ " );
#endif /* mwNew */
#ifdef __STDC__
mwWrite( "__STDC__ " );
#endif /* __STDC__ */
#ifdef mw16BIT
mwWrite( "16-bit " );
#endif
#ifdef mw32BIT
mwWrite( "32-bit " );
#endif
#ifdef mw64BIT
mwWrite( "64-bit " );
#endif
mwWrite( "mwDWORD==(" mwDWORD_DEFINED ")\n" );
mwWrite( "mwROUNDALLOC==%d sizeof(mwData)==%d mwDataSize==%d\n",
mwROUNDALLOC, sizeof(mwData), mwDataSize );
/**************************************************************** Generic */
/************************************************************ Microsoft C */
#ifdef _MSC_VER
mwWrite( "Compiled using Microsoft C" CPPTEXT
" %d.%02d\n", _MSC_VER / 100, _MSC_VER % 100 );
#endif /* _MSC_VER */
/************************************************************ Microsoft C */
/************************************************************** Borland C */
#ifdef __BORLANDC__
mwWrite( "Compiled using Borland C"
#ifdef __cplusplus
"++ %d.%01d\n", __BCPLUSPLUS__/0x100, (__BCPLUSPLUS__%0x100)/0x10 );
#else
" %d.%01d\n", __BORLANDC__/0x100, (__BORLANDC__%0x100)/0x10 );
#endif /* __cplusplus */
#endif /* __BORLANDC__ */
/************************************************************** Borland C */
/************************************************************** Watcom C */
#ifdef __WATCOMC__
mwWrite( "Compiled using Watcom C %d.%02d ",
__WATCOMC__/100, __WATCOMC__%100 );
#ifdef __FLAT__
mwWrite( "(32-bit flat model)" );
#endif /* __FLAT__ */
mwWrite( "\n" );
#endif /* __WATCOMC__ */
/************************************************************** Watcom C */
mwWrite( "\n" );
FLUSH();
}
if( mwUseAtexit ) (void) atexit( mwAbort );
return;
}
void mwAbort( void ) {
mwData *mw;
mwMarker *mrk;
char *data;
time_t tid;
int c, i, j;
int errors;
tid = time( NULL );
mwWrite( "\nStopped at %s\n", ctime( &tid) );
if( !mwInited )
mwWrite( "internal: mwAbort(): MEMWATCH not initialized!\n" );
/* release the grab list */
mwDropAll();
/* report mwMarked items */
while( mwFirstMark ) {
mrk = mwFirstMark->next;
mwWrite( "mark: %p: %s\n", mwFirstMark->host, mwFirstMark->text );
free( mwFirstMark->text );
free( mwFirstMark );
mwFirstMark = mrk;
mwErrors ++;
}
/* release all still allocated memory */
errors = 0;
while( mwHead != NULL && errors < 3 ) {
if( !mwIsOwned(mwHead, __FILE__, __LINE__ ) ) {
if( errors < 3 )
{
errors ++;
mwWrite( "internal: NML/unfreed scan restarting\n" );
FLUSH();
mwHead = mwHead;
continue;
}
mwWrite( "internal: NML/unfreed scan aborted, heap too damaged\n" );
FLUSH();
break;
}
mwFlushW(0);
if( !(mwHead->flag & MW_NML) ) {
mwErrors++;
data = ((char*)mwHead)+mwDataSize;
mwWrite( "unfreed: <%ld> %s(%d), %ld bytes at %p ",
mwHead->count, mwHead->file, mwHead->line, (long)mwHead->size, data+mwOverflowZoneSize );
if( mwCheckOF( data ) ) {
mwWrite( "[underflowed] ");
FLUSH();
}
if( mwCheckOF( (data+mwOverflowZoneSize+mwHead->size) ) ) {
mwWrite( "[overflowed] ");
FLUSH();
}
mwWrite( " \t{" );
j = 16; if( mwHead->size < 16 ) j = (int) mwHead->size;
for( i=0;i<16;i++ ) {
if( i<j ) mwWrite( "%02X ",
(unsigned char) *(data+mwOverflowZoneSize+i) );
else mwWrite( ".. " );
}
for( i=0;i<j;i++ ) {
c = *(data+mwOverflowZoneSize+i);
if( c < 32 || c > 126 ) c = '.';
mwWrite( "%c", c );
}
mwWrite( "}\n" );
mw = mwHead;
mwUnlink( mw, __FILE__, __LINE__ );
free( mw );
}
else {
data = ((char*)mwHead) + mwDataSize + mwOverflowZoneSize;
if( mwTestMem( data, mwHead->size, MW_VAL_NML ) ) {
mwErrors++;
mwWrite( "wild pointer: <%ld> NoMansLand %p alloc'd at %s(%d)\n",
mwHead->count, data + mwOverflowZoneSize, mwHead->file, mwHead->line );
FLUSH();
}
mwNmlNumAlloc --;
mwNmlCurAlloc -= mwHead->size;
mw = mwHead;
mwUnlink( mw, __FILE__, __LINE__ );
free( mw );
}
}
if( mwNmlNumAlloc ) mwWrite("internal: NoMansLand block counter %ld, not zero\n", mwNmlNumAlloc );
if( mwNmlCurAlloc ) mwWrite("internal: NoMansLand byte counter %ld, not zero\n", mwNmlCurAlloc );
/* report statistics */
mwStatReport();
FLUSH();
mwInited = 0;
mwHead = mwTail = NULL;
if( mwErrors )
fprintf(mwSTDERR,"MEMWATCH detected %ld anomalies\n",mwErrors);
mwLogFile( NULL );
mwErrors = 0;
MW_MUTEX_TERM();
}
void mwTerm( void ) {
if( mwInited == 1 )
{
mwAbort();
return;
}
if( !mwInited )
mwWrite("internal: mwTerm(): MEMWATCH has not been started!\n");
else
mwInited --;
}
void mwStatistics( int level )
{
mwAutoInit();
if( level<0 ) level=0;
if( mwStatLevel != level )
{
mwWrite( "statistics: now collecting on a %s basis\n",
level<1?"global":(level<2?"module":"line") );
mwStatLevel = level;
}
}
void mwAutoCheck( int onoff ) {
mwAutoInit();
mwTestAlways = onoff;
if( onoff ) mwTestFlags = MW_TEST_ALL;
}
void mwSetOutFunc( void (*func)(int) ) {
mwAutoInit();
mwOutFunction = func;
}
static void mwWriteOF( void *p )
{
int i;
unsigned char *ptr;
ptr = (unsigned char*) p;
for( i=0; i<mwOverflowZoneSize; i++ )
{
*(ptr+i) = mwOverflowZoneTemplate[i%8];
}
return;
}
static int mwCheckOF( const void *p )
{
int i;
const unsigned char *ptr;
ptr = (const unsigned char *) p;
for( i=0; i<mwOverflowZoneSize; i++ )
{
if( *(ptr+i) != mwOverflowZoneTemplate[i%8] )
return 1; /* errors found */
}
return 0; /* no errors */
}
int mwTest( const char *file, int line, int items ) {
mwAutoInit();
mwTestFlags = items;
return mwTestNow( file, line, 0 );
}
/*
** Returns zero if there are no errors.
** Returns nonzero if there are errors.
*/
int mwTestBuffer( const char *file, int line, void *p ) {
mwData* mw;
mwAutoInit();
/* do the quick ownership test */
mw = (mwData*) mwBUFFER_TO_MW( p );
if( mwIsOwned( mw, file, line ) ) {
return mwTestBuf( mw, file, line );
}
return 1;
}
void mwBreakOut( const char* cause ) {
fprintf(mwSTDERR, "breakout: %s\n", cause);
mwWrite("breakout: %s\n", cause );
return;
}
/*
** 981217 JLI: is it possible that ->next is not always set?
*/
void * mwMark( void *p, const char *desc, const char *file, unsigned line ) {
mwMarker *mrk;
unsigned n, isnew;
char *buf;
int tot, oflow = 0;
char wherebuf[128];
mwAutoInit();
TESTS(NULL,0);
if( desc == NULL ) desc = "unknown";
if( file == NULL ) file = "unknown";
tot = sprintf( wherebuf, "%.48s called from %s(%d)", desc, file, line );
if( tot >= (int)sizeof(wherebuf) ) { wherebuf[sizeof(wherebuf)-1] = 0; oflow = 1; }
if( p == NULL ) {
mwWrite("mark: %s(%d), no mark for NULL:'%s' may be set\n", file, line, desc );
return p;
}
if( mwFirstMark != NULL && !mwIsReadAddr( mwFirstMark, sizeof( mwMarker ) ) )
{
mwWrite("mark: %s(%d), mwFirstMark (%p) is trashed, can't mark for %s\n",
file, line, mwFirstMark, desc );
return p;
}
for( mrk=mwFirstMark; mrk; mrk=mrk->next )
{
if( mrk->next != NULL && !mwIsReadAddr( mrk->next, sizeof( mwMarker ) ) )
{
mwWrite("mark: %s(%d), mark(%p)->next(%p) is trashed, can't mark for %s\n",
file, line, mrk, mrk->next, desc );
return p;
}
if( mrk->host == p ) break;
}
if( mrk == NULL ) {
isnew = 1;
mrk = (mwMarker*) malloc( sizeof( mwMarker ) );
if( mrk == NULL ) {
mwWrite("mark: %s(%d), no mark for %p:'%s', out of memory\n", file, line, p, desc );
return p;
}
mrk->next = NULL;
n = 0;
}
else {
isnew = 0;
n = strlen( mrk->text );
}
n += strlen( wherebuf );
buf = (char*) malloc( n+3 );
if( buf == NULL ) {
if( isnew ) free( mrk );
mwWrite("mark: %s(%d), no mark for %p:'%s', out of memory\n", file, line, p, desc );
return p;
}
if( isnew ) {
memcpy( buf, wherebuf, n+1 );
mrk->next = mwFirstMark;
mrk->host = p;
mrk->text = buf;
mrk->level = 1;
mwFirstMark = mrk;
}
else {
strcpy( buf, mrk->text );
strcat( buf, ", " );
strcat( buf, wherebuf );
free( mrk->text );
mrk->text = buf;
mrk->level ++;
}
if( oflow ) {
mwIncErr();
mwTrace( " [WARNING: OUTPUT BUFFER OVERFLOW - SYSTEM UNSTABLE]\n" );
}
return p;
}
void* mwUnmark( void *p, const char *file, unsigned line ) {
mwMarker *mrk, *prv;
mrk = mwFirstMark;
prv = NULL;
while( mrk ) {
if( mrk->host == p ) {
if( mrk->level < 2 ) {
if( prv ) prv->next = mrk->next;
else mwFirstMark = mrk->next;
free( mrk->text );
free( mrk );
return p;
}
mrk->level --;
return p;
}
prv = mrk;
mrk = mrk->next;
}
mwWrite("mark: %s(%d), no mark found for %p\n", file, line, p );
return p;
}
/***********************************************************************
** Abort/Retry/Ignore handlers
***********************************************************************/
static int mwARI( const char *estr ) {
char inbuf[81];
int c;
fprintf(mwSTDERR, "\n%s\nMEMWATCH: Abort, Retry or Ignore? ", estr);
(void) fgets(inbuf,sizeof(inbuf),stdin);
for( c=0; inbuf[c] && inbuf[c] <= ' '; c++ ) ;
c = inbuf[c];
if( c == 'R' || c == 'r' ) {
mwBreakOut( estr );
return MW_ARI_RETRY;
}
if( c == 'I' || c == 'i' ) return MW_ARI_IGNORE;
return MW_ARI_ABORT;
}
/* standard ARI handler (exported) */
int mwAriHandler( const char *estr ) {
mwAutoInit();
return mwARI( estr );
}
/* used to set the ARI function */
void mwSetAriFunc( int (*func)(const char *) ) {
mwAutoInit();
mwAriFunction = func;
}
/***********************************************************************
** Allocation handlers
***********************************************************************/
void* mwMalloc( size_t size, const char* file, int line) {
size_t needed;
mwData *mw;
char *ptr;
void *p;
mwAutoInit();
MW_MUTEX_LOCK();
TESTS(file,line);
mwCounter ++;
needed = mwDataSize + mwOverflowZoneSize*2 + size;
if( needed < size )
{
/* theoretical case: req size + mw overhead exceeded size_t limits */
return NULL;
}
/* if this allocation would violate the limit, fail it */
if( mwUseLimit && ((long)size + mwStatCurAlloc > mwAllocLimit) ) {
mwWrite( "limit fail: <%ld> %s(%d), %ld wanted %ld available\n",
mwCounter, file, line, (long)size, mwAllocLimit - mwStatCurAlloc );
mwIncErr();
FLUSH();
MW_MUTEX_UNLOCK();
return NULL;
}
mw = (mwData*) malloc( needed );
if( mw == NULL ) {
if( mwFreeUp(needed,0) >= needed ) {
mw = (mwData*) malloc(needed);
if( mw == NULL ) {
mwWrite( "internal: mwFreeUp(%u) reported success, but malloc() fails\n", needed );
mwIncErr();
FLUSH();
}
}
if( mw == NULL ) {
mwWrite( "fail: <%ld> %s(%d), %ld wanted %ld allocated\n",
mwCounter, file, line, (long)size, mwStatCurAlloc );
mwIncErr();
FLUSH();
MW_MUTEX_UNLOCK();
return NULL;
}
}
mw->count = mwCounter;
mw->prev = NULL;
mw->next = mwHead;
mw->file = file;
mw->size = size;
mw->line = line;
mw->flag = 0;
mw->check = CHKVAL(mw);
if( mwHead ) mwHead->prev = mw;
mwHead = mw;
if( mwTail == NULL ) mwTail = mw;
ptr = ((char*)mw) + mwDataSize;
mwWriteOF( ptr ); /* '*(long*)ptr = PRECHK;' */
ptr += mwOverflowZoneSize;
p = ptr;
memset( ptr, MW_VAL_NEW, size );
ptr += size;
mwWriteOF( ptr ); /* '*(long*)ptr = POSTCHK;' */
mwNumCurAlloc ++;
mwStatCurAlloc += (long) size;
mwStatTotAlloc += (long) size;
if( mwStatCurAlloc > mwStatMaxAlloc )
mwStatMaxAlloc = mwStatCurAlloc;
mwStatNumAlloc ++;
if( mwStatLevel ) mwStatAlloc( size, file, line );
MW_MUTEX_UNLOCK();
return p;
}
void* mwRealloc( void *p, size_t size, const char* file, int line) {
int oldUseLimit, i;
mwData *mw;
char *ptr;
mwAutoInit();
if( p == NULL ) return mwMalloc( size, file, line );
if( size == 0 ) { mwFree( p, file, line ); return NULL; }
MW_MUTEX_LOCK();
/* do the quick ownership test */
mw = (mwData*) mwBUFFER_TO_MW( p );
if( mwIsOwned( mw, file, line ) ) {
/* if the buffer is an NML, treat this as a double-free */
if( mw->flag & MW_NML )
{
mwIncErr();
if( *((unsigned char*)(mw)+mwDataSize+mwOverflowZoneSize) != MW_VAL_NML )
{
mwWrite( "internal: <%ld> %s(%d), no-mans-land MW-%p is corrupted\n",
mwCounter, file, line, mw );
}
goto check_dbl_free;
}
/* if this allocation would violate the limit, fail it */
if( mwUseLimit && ((long)size + mwStatCurAlloc - (long)mw->size > mwAllocLimit) ) {
TESTS(file,line);
mwCounter ++;
mwWrite( "limit fail: <%ld> %s(%d), %ld wanted %ld available\n",
mwCounter, file, line, (unsigned long)size - mw->size, mwAllocLimit - mwStatCurAlloc );
mwIncErr();
FLUSH();
MW_MUTEX_UNLOCK();
return NULL;
}
/* fake realloc operation */
oldUseLimit = mwUseLimit;
mwUseLimit = 0;
ptr = (char*) mwMalloc( size, file, line );
if( ptr != NULL ) {
if( size < mw->size )
memcpy( ptr, p, size );
else
memcpy( ptr, p, mw->size );
mwFree( p, file, line );
}
mwUseLimit = oldUseLimit;
MW_MUTEX_UNLOCK();
return (void*) ptr;
}
/* Unknown pointer! */
/* using free'd pointer? */
check_dbl_free:
for(i=0;i<MW_FREE_LIST;i++) {
if( mwLastFree[i] == p ) {
mwIncErr();
mwWrite( "realloc: <%ld> %s(%d), %p was"
" freed from %s(%d)\n",
mwCounter, file, line, p,
mwLFfile[i], mwLFline[i] );
FLUSH();
MW_MUTEX_UNLOCK();
return NULL;
}
}
/* some weird pointer */
mwIncErr();
mwWrite( "realloc: <%ld> %s(%d), unknown pointer %p\n",
mwCounter, file, line, p );
FLUSH();
MW_MUTEX_UNLOCK();
return NULL;
}
char *mwStrdup( const char* str, const char* file, int line ) {
size_t len;
char *newstring;
MW_MUTEX_LOCK();
if( str == NULL ) {
mwIncErr();
mwWrite( "strdup: <%ld> %s(%d), strdup(NULL) called\n",
mwCounter, file, line );
FLUSH();
MW_MUTEX_UNLOCK();
return NULL;
}
len = strlen( str ) + 1;
newstring = (char*) mwMalloc( len, file, line );
if( newstring != NULL ) memcpy( newstring, str, len );
MW_MUTEX_UNLOCK();
return newstring;
}
void mwFree( void* p, const char* file, int line ) {
int i;
mwData* mw;
char buffer[ sizeof(mwData) + (mwROUNDALLOC*3) + 64 ];
/* this code is in support of C++ delete */
if( file == NULL ) {
mwFree_( p );
MW_MUTEX_UNLOCK();
return;
}
mwAutoInit();
MW_MUTEX_LOCK();
TESTS(file,line);
mwCounter ++;
/* on NULL free, write a warning and return */
if( p == NULL ) {
mwWrite( "NULL free: <%ld> %s(%d), NULL pointer free'd\n",
mwCounter, file, line );
FLUSH();
MW_MUTEX_UNLOCK();
return;
}
/* do the quick ownership test */
mw = (mwData*) mwBUFFER_TO_MW( p );
if( mwIsOwned( mw, file, line ) ) {
(void) mwTestBuf( mw, file, line );
/* if the buffer is an NML, treat this as a double-free */
if( mw->flag & MW_NML )
{
if( *(((unsigned char*)mw)+mwDataSize+mwOverflowZoneSize) != MW_VAL_NML )
{
mwWrite( "internal: <%ld> %s(%d), no-mans-land MW-%p is corrupted\n",
mwCounter, file, line, mw );
}
goto check_dbl_free;
}
/* update the statistics */
mwNumCurAlloc --;
mwStatCurAlloc -= (long) mw->size;
if( mwStatLevel ) mwStatFree( mw->size, mw->file, mw->line );
/* we should either free the allocation or keep it as NML */
if( mwNML ) {
mw->flag |= MW_NML;
mwNmlNumAlloc ++;
mwNmlCurAlloc += (long) mw->size;
memset( ((char*)mw)+mwDataSize+mwOverflowZoneSize, MW_VAL_NML, mw->size );
}
else {
/* unlink the allocation, and enter the post-free data */
mwUnlink( mw, file, line );
memset( mw, MW_VAL_DEL,
mw->size + mwDataSize+mwOverflowZoneSize+mwOverflowZoneSize );
if( mwFBI ) {
memset( mw, '.', mwDataSize + mwOverflowZoneSize );
sprintf( buffer, "FBI<%ld>%s(%d)", mwCounter, file, line );
strncpy( (char*)(void*)mw, buffer, mwDataSize + mwOverflowZoneSize );
}
free( mw );
}
/* add the pointer to the last-free track */
mwLFfile[ mwLFcur ] = file;
mwLFline[ mwLFcur ] = line;
mwLastFree[ mwLFcur++ ] = p;
if( mwLFcur == MW_FREE_LIST ) mwLFcur = 0;
MW_MUTEX_UNLOCK();
return;
}
/* check for double-freeing */
check_dbl_free:
for(i=0;i<MW_FREE_LIST;i++) {
if( mwLastFree[i] == p ) {
mwIncErr();
mwWrite( "double-free: <%ld> %s(%d), %p was"
" freed from %s(%d)\n",
mwCounter, file, line, p,
mwLFfile[i], mwLFline[i] );
FLUSH();
MW_MUTEX_UNLOCK();
return;
}
}
/* some weird pointer... block the free */
mwIncErr();
mwWrite( "WILD free: <%ld> %s(%d), unknown pointer %p\n",
mwCounter, file, line, p );
FLUSH();
MW_MUTEX_UNLOCK();
return;
}
void* mwCalloc( size_t a, size_t b, const char *file, int line ) {
void *p;
size_t size = a * b;
p = mwMalloc( size, file, line );
if( p == NULL ) return NULL;
memset( p, 0, size );
return p;
}
void mwFree_( void *p ) {
MW_MUTEX_LOCK();
TESTS(NULL,0);
MW_MUTEX_UNLOCK();
free(p);
}
void* mwMalloc_( size_t size ) {
MW_MUTEX_LOCK();
TESTS(NULL,0);
MW_MUTEX_UNLOCK();
return malloc( size );
}
void* mwRealloc_( void *p, size_t size ) {
MW_MUTEX_LOCK();
TESTS(NULL,0);
MW_MUTEX_UNLOCK();
return realloc( p, size );
}
void* mwCalloc_( size_t a, size_t b ) {
MW_MUTEX_LOCK();
TESTS(NULL,0);
MW_MUTEX_UNLOCK();
return calloc( a, b );
}
void mwFlushNow( void ) {
if( mwLogR() ) fflush( mwLogR() );
return;
}
void mwDoFlush( int onoff ) {
mwFlushW( onoff<1?0:onoff );
if( onoff ) if( mwLogR() ) fflush( mwLogR() );
return;
}
void mwLimit( long lim ) {
TESTS(NULL,0);
mwWrite("limit: old limit = ");
if( !mwAllocLimit ) mwWrite( "none" );
else mwWrite( "%ld bytes", mwAllocLimit );
mwWrite( ", new limit = ");
if( !lim ) {
mwWrite( "none\n" );
mwUseLimit = 0;
}
else {
mwWrite( "%ld bytes\n", lim );
mwUseLimit = 1;
}
mwAllocLimit = lim;
FLUSH();
}
void mwSetAriAction( int action ) {
MW_MUTEX_LOCK();
TESTS(NULL,0);
mwAriAction = action;
MW_MUTEX_UNLOCK();
return;
}
int mwAssert( int exp, const char *exps, const char *fn, int ln ) {
int i;
char buffer[MW_TRACE_BUFFER+8];
if( exp ) {
return 0;
}
mwAutoInit();
MW_MUTEX_LOCK();
TESTS(fn,ln);
mwIncErr();
mwCounter++;
mwWrite( "assert trap: <%ld> %s(%d), %s\n", mwCounter, fn, ln, exps );
if( mwAriFunction != NULL ) {
sprintf( buffer, "MEMWATCH: assert trap: %s(%d), %s", fn, ln, exps );
i = (*mwAriFunction)(buffer);
switch( i ) {
case MW_ARI_IGNORE:
mwWrite( "assert trap: <%ld> IGNORED - execution continues\n", mwCounter );
MW_MUTEX_UNLOCK();
return 0;
case MW_ARI_RETRY:
mwWrite( "assert trap: <%ld> RETRY - executing again\n", mwCounter );
MW_MUTEX_UNLOCK();
return 1;
}
}
else {
if( mwAriAction & MW_ARI_IGNORE ) {
mwWrite( "assert trap: <%ld> AUTO IGNORED - execution continues\n", mwCounter );
MW_MUTEX_UNLOCK();
return 0;
}
fprintf(mwSTDERR,"\nMEMWATCH: assert trap: %s(%d), %s\n", fn, ln, exps );
}
FLUSH();
(void) mwTestNow( fn, ln, 1 );
FLUSH();
if( mwAriAction & MW_ARI_NULLREAD ) {
/* This is made in an attempt to kick in */
/* any debuggers or OS stack traces */
FLUSH();
/*lint -save -e413 */
i = *((int*)NULL);
mwDummy( (char)i );
/*lint -restore */
}
MW_MUTEX_UNLOCK();
exit(255);
/* NOT REACHED - the return statement is in to keep */
/* stupid compilers from squeaking about differing return modes. */
/* Smart compilers instead say 'code unreachable...' */
/*lint -save -e527 */
return 0;
/*lint -restore */
}
int mwVerify( int exp, const char *exps, const char *fn, int ln ) {
int i;
char buffer[MW_TRACE_BUFFER+8];
if( exp ) {
return 0;
}
mwAutoInit();
MW_MUTEX_LOCK();
TESTS(fn,ln);
mwIncErr();
mwCounter++;
mwWrite( "verify trap: <%ld> %s(%d), %s\n", mwCounter, fn, ln, exps );
if( mwAriFunction != NULL ) {
sprintf( buffer, "MEMWATCH: verify trap: %s(%d), %s", fn, ln, exps );
i = (*mwAriFunction)(buffer);
if( i == 0 ) {
mwWrite( "verify trap: <%ld> IGNORED - execution continues\n", mwCounter );
MW_MUTEX_UNLOCK();
return 0;
}
if( i == 1 ) {
mwWrite( "verify trap: <%ld> RETRY - executing again\n", mwCounter );
MW_MUTEX_UNLOCK();
return 1;
}
}
else {
if( mwAriAction & MW_ARI_NULLREAD ) {
/* This is made in an attempt to kick in */
/* any debuggers or OS stack traces */
FLUSH();
/*lint -save -e413 */
i = *((int*)NULL);
mwDummy( (char)i );
/*lint -restore */
}
if( mwAriAction & MW_ARI_IGNORE ) {
mwWrite( "verify trap: <%ld> AUTO IGNORED - execution continues\n", mwCounter );
MW_MUTEX_UNLOCK();
return 0;
}
fprintf(mwSTDERR,"\nMEMWATCH: verify trap: %s(%d), %s\n", fn, ln, exps );
}
FLUSH();
(void) mwTestNow( fn, ln, 1 );
FLUSH();
MW_MUTEX_UNLOCK();
exit(255);
/* NOT REACHED - the return statement is in to keep */
/* stupid compilers from squeaking about differing return modes. */
/* Smart compilers instead say 'code unreachable...' */
/*lint -save -e527 */
return 0;
/*lint -restore */
}
void mwTrace( const char *format, ... ) {
int tot, oflow = 0;
va_list mark;
mwAutoInit();
MW_MUTEX_LOCK();
TESTS(NULL,0);
if( mwOutFunction == NULL ) mwOutFunction = mwDefaultOutFunc;
va_start( mark, format );
tot = vsprintf( mwPrintBuf, format, mark );
va_end( mark );
if( tot >= MW_TRACE_BUFFER ) { mwPrintBuf[MW_TRACE_BUFFER] = 0; oflow = 1; }
for(tot=0;mwPrintBuf[tot];tot++)
(*mwOutFunction)( mwPrintBuf[tot] );
if( oflow ) {
mwIncErr();
mwTrace( " [WARNING: OUTPUT BUFFER OVERFLOW - SYSTEM UNSTABLE]\n" );
}
FLUSH();
MW_MUTEX_UNLOCK();
}
/***********************************************************************
** Grab & Drop
***********************************************************************/
unsigned mwGrab( unsigned kb ) {
TESTS(NULL,0);
return mwGrab_( kb, MW_VAL_GRB, 0 );
}
unsigned mwDrop( unsigned kb ) {
TESTS(NULL,0);
return mwDrop_( kb, MW_VAL_GRB, 0 );
}
static void mwDropAll() {
TESTS(NULL,0);
(void) mwDrop_( 0, MW_VAL_GRB, 0 );
(void) mwDrop_( 0, MW_VAL_NML, 0 );
if( mwGrabList != NULL )
mwWrite( "internal: the grab list is not empty after mwDropAll()\n");
}
static const char *mwGrabType( int type ) {
switch( type ) {
case MW_VAL_GRB:
return "grabbed";
case MW_VAL_NML:
return "no-mans-land";
default:
/* do nothing */
;
}
return "<unknown type>";
}
static unsigned mwGrab_( unsigned kb, int type, int silent ) {
unsigned i = kb;
mwGrabData *gd;
if( !kb ) i = kb = 65000U;
for(;kb;kb--) {
if( mwUseLimit &&
(mwStatCurAlloc + mwGrabSize + (long)sizeof(mwGrabData) > mwAllocLimit) ) {
if( !silent ) {
mwWrite("grabbed: all allowed memory to %s (%u kb)\n",
mwGrabType(type), i-kb);
FLUSH();
}
return i-kb;
}
gd = (mwGrabData*) malloc( sizeof(mwGrabData) );
if( gd == NULL ) {
if( !silent ) {
mwWrite("grabbed: all available memory to %s (%u kb)\n",
mwGrabType(type), i-kb);
FLUSH();
}
return i-kb;
}
mwGrabSize += (long) sizeof(mwGrabData);
gd->next = mwGrabList;
memset( gd->blob, type, sizeof(gd->blob) );
gd->type = type;
mwGrabList = gd;
}
if( !silent ) {
mwWrite("grabbed: %u kilobytes of %s memory\n", i, mwGrabType(type) );
FLUSH();
}
return i;
}
static unsigned mwDrop_( unsigned kb, int type, int silent ) {
unsigned i = kb;
mwGrabData *gd,*tmp,*pr;
const void *p;
if( mwGrabList == NULL && kb == 0 ) return 0;
if( !kb ) i = kb = 60000U;
pr = NULL;
gd = mwGrabList;
for(;kb;) {
if( gd == NULL ) {
if( i-kb > 0 && !silent ) {
mwWrite("dropped: all %s memory (%u kb)\n", mwGrabType(type), i-kb);
FLUSH();
}
return i-kb;
}
if( gd->type == type ) {
if( pr ) pr->next = gd->next;
kb --;
tmp = gd;
if( mwGrabList == gd ) mwGrabList = gd->next;
gd = gd->next;
p = mwTestMem( tmp->blob, sizeof( tmp->blob ), type );
if( p != NULL ) {
mwWrite( "wild pointer: <%ld> %s memory hit at %p\n",
mwCounter, mwGrabType(type), p );
FLUSH();
}
mwGrabSize -= (long) sizeof(mwGrabData);
free( tmp );
}
else {
pr = gd;
gd = gd->next;
}
}
if( !silent ) {
mwWrite("dropped: %u kilobytes of %s memory\n", i, mwGrabType(type) );
FLUSH();
}
return i;
}
/***********************************************************************
** No-Mans-Land
***********************************************************************/
void mwNoMansLand( int level ) {
mwAutoInit();
TESTS(NULL,0);
switch( level ) {
case MW_NML_NONE:
(void) mwDrop_( 0, MW_VAL_NML, 0 );
break;
case MW_NML_FREE:
break;
case MW_NML_ALL:
(void) mwGrab_( 0, MW_VAL_NML, 0 );
break;
default:
return;
}
mwNML = level;
}
/***********************************************************************
** Static functions
***********************************************************************/
static void mwAutoInit( void )
{
if( mwInited ) return;
mwUseAtexit = 1;
mwInit();
return;
}
static FILE *mwLogR() {
if( (mwLog == mwLogB1) && (mwLog == mwLogB2) ) return mwLog;
if( mwLog == mwLogB1 ) mwLogB2 = mwLog;
if( mwLog == mwLogB2 ) mwLogB1 = mwLog;
if( mwLogB1 == mwLogB2 ) mwLog = mwLogB1;
if( (mwLog == mwLogB1) && (mwLog == mwLogB2) ) {
mwWrite("internal: log file handle damaged and recovered\n");
FLUSH();
return mwLog;
}
fprintf(mwSTDERR,"\nMEMWATCH: log file handle destroyed, using mwSTDERR\n" );
mwLog = mwLogB1 = mwLogB2 = mwSTDERR;
return mwSTDERR;
}
static void mwLogW( FILE *p ) {
mwLog = mwLogB1 = mwLogB2 = p;
}
static int mwFlushR() {
if( (mwFlushing == mwFlushingB1) && (mwFlushing == mwFlushingB2) ) return mwFlushing;
if( mwFlushing == mwFlushingB1 ) mwFlushingB2 = mwFlushing;
if( mwFlushing == mwFlushingB2 ) mwFlushingB1 = mwFlushing;
if( mwFlushingB1 == mwFlushingB2 ) mwFlushing = mwFlushingB1;
if( (mwFlushing == mwFlushingB1) && (mwFlushing == mwFlushingB2) ) {
mwWrite("internal: flushing flag damaged and recovered\n");
FLUSH();
return mwFlushing;
}
mwWrite("internal: flushing flag destroyed, so set to true\n");
mwFlushing = mwFlushingB1 = mwFlushingB2 = 1;
return 1;
}
static void mwFlushW( int n ) {
mwFlushing = mwFlushingB1 = mwFlushingB2 = n;
}
static void mwIncErr() {
mwErrors++;
mwFlushW( mwFlushR()+1 );
FLUSH();
}
static void mwFlush() {
if( mwLogR() == NULL ) return;
#ifdef MW_FLUSH
fflush( mwLogR() );
#else
if( mwFlushR() ) fflush( mwLogR() );
#endif
return;
}
static void mwUnlink( mwData* mw, const char* file, int line ) {
if( mw->prev == NULL ) {
if( mwHead != mw )
mwWrite( "internal: <%ld> %s(%d), MW-%p: link1 NULL, but not head\n",
mwCounter, file, line, mw );
mwHead = mw->next;
}
else {
if( mw->prev->next != mw )
mwWrite( "internal: <%ld> %s(%d), MW-%p: link1 failure\n",
mwCounter, file, line, mw );
else mw->prev->next = mw->next;
}
if( mw->next == NULL ) {
if( mwTail != mw )
mwWrite( "internal: <%ld> %s(%d), MW-%p: link2 NULL, but not tail\n",
mwCounter, file, line, mw );
mwTail = mw->prev;
}
else {
if( mw->next->prev != mw )
mwWrite( "internal: <%ld> %s(%d), MW-%p: link2 failure\n",
mwCounter, file, line, mw );
else mw->next->prev = mw->prev;
}
}
/*
** Relinking tries to repair a damaged mw block.
** Returns nonzero if it thinks it successfully
** repaired the heap chain.
*/
static int mwRelink( mwData* mw, const char* file, int line ) {
int fails;
mwData *mw1, *mw2;
long count, size;
mwStat *ms;
if( file == NULL ) file = "unknown";
if( mw == NULL ) {
mwWrite("relink: cannot repair MW at NULL\n");
FLUSH();
goto emergency;
}
if( !mwIsSafeAddr(mw, mwDataSize) ) {
mwWrite("relink: MW-%p is a garbage pointer\n", mw);
FLUSH();
goto emergency;
}
mwWrite("relink: <%ld> %s(%d) attempting to repair MW-%p...\n", mwCounter, file, line, mw );
FLUSH();
fails = 0;
/* Repair from head */
if( mwHead != mw ) {
if( !mwIsSafeAddr( mwHead, mwDataSize ) ) {
mwWrite("relink: failed for MW-%p; head pointer destroyed\n", mw );
FLUSH();
goto emergency;
}
for( mw1=mwHead; mw1; mw1=mw1->next ) {
if( mw1->next == mw ) {
mw->prev = mw1;
break;
}
if( mw1->next &&
( !mwIsSafeAddr(mw1->next, mwDataSize ) || mw1->next->prev != mw1) ) {
mwWrite("relink: failed for MW-%p; forward chain fragmented at MW-%p: 'next' is %p\n", mw, mw1, mw1->next );
FLUSH();
goto emergency;
}
}
if( mw1 == NULL ) {
mwWrite("relink: MW-%p not found in forward chain search\n", mw );
FLUSH();
fails ++;
}
}
else
{
mwWrite( "relink: MW-%p is the head (first) allocation\n", mw );
if( mw->prev != NULL )
{
mwWrite( "relink: MW-%p prev pointer is non-NULL, you have a wild pointer\n", mw );
mw->prev = NULL;
}
}
/* Repair from tail */
if( mwTail != mw ) {
if( !mwIsSafeAddr( mwTail, mwDataSize ) ) {
mwWrite("relink: failed for MW-%p; tail pointer destroyed\n", mw );
FLUSH();
goto emergency;
}
for( mw1=mwTail; mw1; mw1=mw1->prev ) {
if( mw1->prev == mw ) {
mw->next = mw1;
break;
}
if( mw1->prev && (!mwIsSafeAddr(mw1->prev, mwDataSize ) || mw1->prev->next != mw1) ) {
mwWrite("relink: failed for MW-%p; reverse chain fragmented at MW-%p, 'prev' is %p\n", mw, mw1, mw1->prev );
FLUSH();
goto emergency;
}
}
if( mw1 == NULL ) {
mwWrite("relink: MW-%p not found in reverse chain search\n", mw );
FLUSH();
fails ++;
}
}
else
{
mwWrite( "relink: MW-%p is the tail (last) allocation\n", mw );
if( mw->next != NULL )
{
mwWrite( "relink: MW-%p next pointer is non-NULL, you have a wild pointer\n", mw );
mw->next = NULL;
}
}
if( fails > 1 ) {
mwWrite("relink: heap appears intact, MW-%p probably garbage pointer\n", mw );
FLUSH();
goto verifyok;
}
/* restore MW info where possible */
if( mwIsReadAddr( mw->file, 1 ) ) {
ms = mwStatGet( mw->file, -1, 0 );
if( ms == NULL ) mw->file = "<relinked>";
}
mw->check = CHKVAL(mw);
goto verifyok;
/* Emergency repair */
emergency:
if( mwHead == NULL && mwTail == NULL )
{
if( mwStatCurAlloc == 0 )
mwWrite("relink: <%ld> %s(%d) heap is empty, nothing to repair\n", mwCounter, file, line );
else
mwWrite("relink: <%ld> %s(%d) heap damaged beyond repair\n", mwCounter, file, line );
FLUSH();
return 0;
}
mwWrite("relink: <%ld> %s(%d) attempting emergency repairs...\n", mwCounter, file, line );
FLUSH();
if( mwHead == NULL || mwTail == NULL )
{
if( mwHead == NULL ) mwWrite("relink: mwHead is NULL, but mwTail is %p\n", mwTail );
else mwWrite("relink: mwTail is NULL, but mwHead is %p\n", mwHead );
}
mw1=NULL;
if( mwHead != NULL )
{
if( !mwIsReadAddr( mwHead, mwDataSize ) || mwHead->check != CHKVAL(mwHead) )
{
mwWrite("relink: mwHead (MW-%p) is damaged, skipping forward scan\n", mwHead );
mwHead = NULL;
goto scan_reverse;
}
if( mwHead->prev != NULL )
{
mwWrite("relink: the mwHead pointer's 'prev' member is %p, not NULL\n", mwHead->prev );
}
for( mw1=mwHead; mw1; mw1=mw1->next )
{
if( mw1->next )
{
if( !mwIsReadAddr(mw1->next,mwDataSize) ||
!mw1->next->check != CHKVAL(mw1) ||
mw1->next->prev != mw1 )
{
mwWrite("relink: forward chain's last intact MW is MW-%p, %ld %sbytes at %s(%d)\n",
mw1, mw1->size, (mw->flag & MW_NML)?"NoMansLand ":"", mw1->file, mw1->line );
if( mwIsReadAddr(mw1->next,mwDataSize ) )
{
mwWrite("relink: forward chain's first damaged MW is MW-%p, %ld %sbytes at %s(%d)\n",
mw1->next, mw1->size, (mw->flag & MW_NML)?"NoMansLand ":"",
mwIsReadAddr(mw1->file,16)?mw1->file:"<garbage-pointer>", mw1->line );
}
else
{
mwWrite("relink: the 'next' pointer of this MW points to %p, which is out-of-legal-access\n",
mw1->next );
}
break;
}
}
}
}
scan_reverse:
mw2=NULL;
if( mwTail != NULL )
{
if( !mwIsReadAddr(mwTail,mwDataSize) || mwTail->check != CHKVAL(mwTail) )
{
mwWrite("relink: mwTail (%p) is damaged, skipping reverse scan\n", mwTail );
mwTail = NULL;
goto analyze;
}
if( mwTail->next != NULL )
{
mwWrite("relink: the mwTail pointer's 'next' member is %p, not NULL\n", mwTail->next );
}
for( mw2=mwTail; mw2; mw2=mw2->prev )
{
if( mw2->prev )
{
if( !mwIsReadAddr(mw2->prev,mwDataSize) ||
!mw2->prev->check != CHKVAL(mw2) ||
mw2->prev->next != mw2 )
{
mwWrite("relink: reverse chain's last intact MW is MW-%p, %ld %sbytes at %s(%d)\n",
mw2, mw2->size, (mw->flag & MW_NML)?"NoMansLand ":"", mw2->file, mw2->line );
if( mwIsReadAddr(mw2->prev,mwDataSize ) )
{
mwWrite("relink: reverse chain's first damaged MW is MW-%p, %ld %sbytes at %s(%d)\n",
mw2->prev, mw2->size, (mw->flag & MW_NML)?"NoMansLand ":"",
mwIsReadAddr(mw2->file,16)?mw2->file:"<garbage-pointer>", mw2->line );
}
else
{
mwWrite("relink: the 'prev' pointer of this MW points to %p, which is out-of-legal-access\n",
mw2->prev );
}
break;
}
}
}
}
analyze:
if( mwHead == NULL && mwTail == NULL )
{
mwWrite("relink: both head and tail pointers damaged, aborting program\n");
mwFlushW(1);
FLUSH();
abort();
}
if( mwHead == NULL )
{
mwHead = mw2;
mwWrite("relink: heap truncated, MW-%p designated as new mwHead\n", mw2 );
mw2->prev = NULL;
mw1 = mw2 = NULL;
}
if( mwTail == NULL )
{
mwTail = mw1;
mwWrite("relink: heap truncated, MW-%p designated as new mwTail\n", mw1 );
mw1->next = NULL;
mw1 = mw2 = NULL;
}
if( mw1 == NULL && mw2 == NULL &&
mwHead->prev == NULL && mwTail->next == NULL ) {
mwWrite("relink: verifying heap integrity...\n" );
FLUSH();
goto verifyok;
}
if( mw1 && mw2 && mw1 != mw2 ) {
mw1->next = mw2;
mw2->prev = mw1;
mwWrite("relink: emergency repairs successful, assessing damage...\n");
FLUSH();
}
else {
mwWrite("relink: heap totally destroyed, aborting program\n");
mwFlushW(1);
FLUSH();
abort();
}
/* Verify by checking that the number of active allocations */
/* match the number of entries in the chain */
verifyok:
if( !mwIsHeapOK( NULL ) ) {
mwWrite("relink: heap verification FAILS - aborting program\n");
mwFlushW(1);
FLUSH();
abort();
}
for( size=count=0, mw1=mwHead; mw1; mw1=mw1->next ) {
count ++;
size += (long) mw1->size;
}
if( count == mwNumCurAlloc ) {
mwWrite("relink: successful, ");
if( size == mwStatCurAlloc ) {
mwWrite("no allocations lost\n");
}
else {
if( mw != NULL ) {
mwWrite("size information lost for MW-%p\n", mw);
mw->size = 0;
}
}
}
else {
mwWrite("relink: partial, %ld MW-blocks of %ld bytes lost\n",
mwNmlNumAlloc+mwNumCurAlloc-count, mwNmlCurAlloc+mwStatCurAlloc-size );
return 0;
}
return 1;
}
/*
** If mwData* is NULL:
** Returns 0 if heap chain is broken.
** Returns 1 if heap chain is intact.
** If mwData* is not NULL:
** Returns 0 if mwData* is missing or if chain is broken.
** Returns 1 if chain is intact and mwData* is found.
*/
static int mwIsHeapOK( mwData *includes_mw ) {
int found = 0;
mwData *mw;
for( mw = mwHead; mw; mw=mw->next ) {
if( includes_mw == mw ) found++;
if( !mwIsSafeAddr( mw, mwDataSize ) ) return 0;
if( mw->prev ) {
if( !mwIsSafeAddr( mw->prev, mwDataSize ) ) return 0;
if( mw==mwHead || mw->prev->next != mw ) return 0;
}
if( mw->next ) {
if( !mwIsSafeAddr( mw->next, mwDataSize ) ) return 0;
if( mw==mwTail || mw->next->prev != mw ) return 0;
}
else if( mw!=mwTail ) return 0;
}
if( includes_mw != NULL && !found ) return 0;
return 1;
}
static int mwIsOwned( mwData* mw, const char *file, int line ) {
int retv;
mwStat *ms;
/* see if the address is legal according to OS */
if( !mwIsSafeAddr( mw, mwDataSize ) ) return 0;
/* make sure we have _anything_ allocated */
if( mwHead == NULL && mwTail == NULL && mwStatCurAlloc == 0 )
return 0;
/* calculate checksum */
if( mw->check != CHKVAL(mw) ) {
/* may be damaged checksum, see if block is in heap */
if( mwIsHeapOK( mw ) ) {
/* damaged checksum, repair it */
mwWrite( "internal: <%ld> %s(%d), checksum for MW-%p is incorrect\n",
mwCounter, file, line, mw );
mwIncErr();
if( mwIsReadAddr( mw->file, 1 ) ) {
ms = mwStatGet( mw->file, -1, 0 );
if( ms == NULL ) mw->file = "<relinked>";
}
else mw->file = "<unknown>";
mw->size = 0;
mw->check = CHKVAL(mw);
return 1;
}
/* no, it's just some garbage data */
return 0;
}
/* check that the non-NULL pointers are safe */
if( mw->prev && !mwIsSafeAddr( mw->prev, mwDataSize ) ) mwRelink( mw, file, line );
if( mw->next && !mwIsSafeAddr( mw->next, mwDataSize ) ) mwRelink( mw, file, line );
/* safe address, checksum OK, proceed with heap checks */
/* see if the block is in the heap */
retv = 0;
if( mw->prev ) { if( mw->prev->next == mw ) retv ++; }
else { if( mwHead == mw ) retv++; }
if( mw->next ) { if( mw->next->prev == mw ) retv ++; }
else { if( mwTail == mw ) retv++; }
if( mw->check == CHKVAL(mw) ) retv ++;
if( retv > 2 ) return 1;
/* block not in heap, check heap for corruption */
if( !mwIsHeapOK( mw ) ) {
if( mwRelink( mw, file, line ) )
return 1;
}
/* unable to repair */
mwWrite( "internal: <%ld> %s(%d), mwIsOwned fails for MW-%p\n",
mwCounter, file, line, mw );
mwIncErr();
return 0;
}
/*
** mwTestBuf:
** Checks a buffers links and pre/postfixes.
** Writes errors found to the log.
** Returns zero if no errors found.
*/
static int mwTestBuf( mwData* mw, const char* file, int line ) {
int retv = 0;
char *p;
if( file == NULL ) file = "unknown";
if( !mwIsSafeAddr( mw, mwDataSize + mwOverflowZoneSize ) ) {
mwWrite( "internal: <%ld> %s(%d): pointer MW-%p is invalid\n",
mwCounter, file, line, mw );
mwIncErr();
return 2;
}
if( mw->check != CHKVAL(mw) ) {
mwWrite( "internal: <%ld> %s(%d), info trashed; relinking\n",
mwCounter, file, line );
mwIncErr();
if( !mwRelink( mw, file, line ) ) return 2;
}
if( mw->prev && mw->prev->next != mw ) {
mwWrite( "internal: <%ld> %s(%d), buffer <%ld> %s(%d) link1 broken\n",
mwCounter,file,line, (long)mw->size, mw->count, mw->file, mw->line );
mwIncErr();
if( !mwRelink( mw, file, line ) ) retv = 2;
}
if( mw->next && mw->next->prev != mw ) {
mwWrite( "internal: <%ld> %s(%d), buffer <%ld> %s(%d) link2 broken\n",
mwCounter,file,line, (long)mw->size, mw->count, mw->file, mw->line );
mwIncErr();
if( !mwRelink( mw, file, line ) ) retv = 2;
}
p = ((char*)mw) + mwDataSize;
if( mwCheckOF( p ) ) {
mwWrite( "underflow: <%ld> %s(%d), %ld bytes alloc'd at <%ld> %s(%d)\n",
mwCounter,file,line, (long)mw->size, mw->count, mw->file, mw->line );
mwIncErr();
retv = 1;
}
p += mwOverflowZoneSize + mw->size;
if( mwIsReadAddr( p, mwOverflowZoneSize ) && mwCheckOF( p ) ) {
mwWrite( "overflow: <%ld> %s(%d), %ld bytes alloc'd at <%ld> %s(%d)\n",
mwCounter,file,line, (long)mw->size, mw->count, mw->file, mw->line );
mwIncErr();
retv = 1;
}
return retv;
}
static void mwDefaultOutFunc( int c ) {
if( mwLogR() ) fputc( c, mwLogR() );
}
static void mwWrite( const char *format, ... ) {
int tot, oflow = 0;
va_list mark;
mwAutoInit();
if( mwOutFunction == NULL ) mwOutFunction = mwDefaultOutFunc;
va_start( mark, format );
tot = vsprintf( mwPrintBuf, format, mark );
va_end( mark );
if( tot >= MW_TRACE_BUFFER ) { mwPrintBuf[MW_TRACE_BUFFER] = 0; oflow = 1; }
for(tot=0;mwPrintBuf[tot];tot++)
(*mwOutFunction)( mwPrintBuf[tot] );
if( oflow ) {
mwWrite( "\ninternal: mwWrite(): WARNING! OUTPUT EXCEEDED %u CHARS: SYSTEM UNSTABLE\n", MW_TRACE_BUFFER-1 );
FLUSH();
}
return;
}
static void mwLogFile( const char *name ) {
time_t tid;
(void) time( &tid );
if( mwLogR() != NULL ) {
fclose( mwLogR() );
mwLogW( NULL );
}
if( name == NULL ) return;
mwLogW( fopen( name, "a" COMMIT ) );
if( mwLogR() == NULL )
mwWrite( "logfile: failed to open/create file '%s'\n", name );
}
/*
** Try to free NML memory until a contiguous allocation of
** 'needed' bytes can be satisfied. If this is not enough
** and the 'urgent' parameter is nonzero, grabbed memory is
** also freed.
*/
static size_t mwFreeUp( size_t needed, int urgent ) {
void *p;
mwData *mw, *mw2;
char *data;
/* free grabbed NML memory */
for(;;) {
if( mwDrop_( 1, MW_VAL_NML, 1 ) == 0 ) break;
p = malloc( needed );
if( p == NULL ) continue;
free( p );
return needed;
}
/* free normal NML memory */
mw = mwHead;
while( mw != NULL ) {
if( !(mw->flag & MW_NML) ) mw = mw->next;
else {
data = ((char*)mw)+mwDataSize+mwOverflowZoneSize;
if( mwTestMem( data, mw->size, MW_VAL_NML ) ) {
mwIncErr();
mwWrite( "wild pointer: <%ld> NoMansLand %p alloc'd at %s(%d)\n",
mw->count, data + mwOverflowZoneSize, mw->file, mw->line );
}
mw2 = mw->next;
mwUnlink( mw, "mwFreeUp", 0 );
free( mw );
mw = mw2;
p = malloc( needed );
if( p == NULL ) continue;
free( p );
return needed;
}
}
/* if not urgent (for internal purposes), fail */
if( !urgent ) return 0;
/* free grabbed memory */
for(;;) {
if( mwDrop_( 1, MW_VAL_GRB, 1 ) == 0 ) break;
p = malloc( needed );
if( p == NULL ) continue;
free( p );
return needed;
}
return 0;
}
static const void * mwTestMem( const void *p, unsigned len, int c ) {
const unsigned char *ptr;
ptr = (const unsigned char *) p;
while( len-- ) {
if( *ptr != (unsigned char)c ) return (const void*)ptr;
ptr ++;
}
return NULL;
}
static int mwStrCmpI( const char *s1, const char *s2 ) {
if( s1 == NULL || s2 == NULL ) return 0;
while( *s1 ) {
if( toupper(*s2) == toupper(*s1) ) { s1++; s2++; continue; }
return 1;
}
return 0;
}
#define AIPH() if( always_invoked ) { mwWrite("autocheck: <%ld> %s(%d) ", mwCounter, file, line ); always_invoked = 0; }
static int mwTestNow( const char *file, int line, int always_invoked ) {
int retv = 0;
mwData *mw;
char *data;
if( file && !always_invoked )
mwWrite("check: <%ld> %s(%d), checking %s%s%s\n",
mwCounter, file, line,
(mwTestFlags & MW_TEST_CHAIN) ? "chain ": "",
(mwTestFlags & MW_TEST_ALLOC) ? "alloc ": "",
(mwTestFlags & MW_TEST_NML) ? "nomansland ": ""
);
if( mwTestFlags & MW_TEST_CHAIN ) {
for( mw = mwHead; mw; mw=mw->next ) {
if( !mwIsSafeAddr(mw, mwDataSize) ) {
AIPH();
mwWrite("check: heap corruption detected\n");
mwIncErr();
return retv + 1;
}
if( mw->prev ) {
if( !mwIsSafeAddr(mw->prev, mwDataSize) ) {
AIPH();
mwWrite("check: heap corruption detected\n");
mwIncErr();
return retv + 1;
}
if( mw==mwHead || mw->prev->next != mw ) {
AIPH();
mwWrite("check: heap chain broken, prev link incorrect\n");
mwIncErr();
retv ++;
}
}
if( mw->next ) {
if( !mwIsSafeAddr(mw->next, mwDataSize) ) {
AIPH();
mwWrite("check: heap corruption detected\n");
mwIncErr();
return retv + 1;
}
if( mw==mwTail || mw->next->prev != mw ) {
AIPH();
mwWrite("check: heap chain broken, next link incorrect\n");
mwIncErr();
retv ++;
}
}
else if( mw!=mwTail ) {
AIPH();
mwWrite("check: heap chain broken, tail incorrect\n");
mwIncErr();
retv ++;
}
}
}
if( mwTestFlags & MW_TEST_ALLOC ) {
for( mw = mwHead; mw; mw=mw->next ) {
if( mwTestBuf( mw, file, line ) ) retv ++;
}
}
if( mwTestFlags & MW_TEST_NML ) {
for( mw = mwHead; mw; mw=mw->next ) {
if( (mw->flag & MW_NML) ) {
data = ((char*)mw)+mwDataSize+mwOverflowZoneSize;
if( mwTestMem( data, mw->size, MW_VAL_NML ) ) {
mwIncErr();
mwWrite( "wild pointer: <%ld> NoMansLand %p alloc'd at %s(%d)\n",
mw->count, data + mwOverflowZoneSize, mw->file, mw->line );
}
}
}
}
if( file && !always_invoked && !retv )
mwWrite("check: <%ld> %s(%d), complete; no errors\n",
mwCounter, file, line );
return retv;
}
/**********************************************************************
** Statistics
**********************************************************************/
static void mwStatReport()
{
mwStat* ms, *ms2;
const char *modname;
int modnamelen;
/* global statistics report */
mwWrite( "\nMemory usage statistics (global):\n" );
mwWrite( " N)umber of allocations made: %ld\n", mwStatNumAlloc );
mwWrite( " L)argest memory usage : %ld\n", mwStatMaxAlloc );
mwWrite( " T)otal of all alloc() calls: %ld\n", mwStatTotAlloc );
mwWrite( " U)nfreed bytes totals : %ld\n", mwStatCurAlloc );
FLUSH();
if( mwStatLevel < 1 ) return;
/* on a per-module basis */
mwWrite( "\nMemory usage statistics (detailed):\n");
mwWrite( " Module/Line Number Largest Total Unfreed \n");
for( ms=mwStatList; ms; ms=ms->next )
{
if( ms->line == -1 )
{
if( ms->file == NULL || !mwIsReadAddr(ms->file,22) ) modname = "<unknown>";
else modname = ms->file;
modnamelen = strlen(modname);
if( modnamelen > 42 )
{
modname = modname + modnamelen - 42;
}
mwWrite(" %-42s %-8ld %-8ld %-8ld %-8ld\n",
modname, ms->num, ms->max, ms->total, ms->curr );
if( ms->file && mwStatLevel > 1 )
{
for( ms2=mwStatList; ms2; ms2=ms2->next )
{
if( ms2->line!=-1 && ms2->file!=NULL && !mwStrCmpI( ms2->file, ms->file ) )
{
mwWrite( " %-8d %-8ld %-8ld %-8ld %-8ld\n",
ms2->line, ms2->num, ms2->max, ms2->total, ms2->curr );
}
}
}
}
}
}
static mwStat* mwStatGet( const char *file, int line, int makenew ) {
mwStat* ms;
if( mwStatLevel < 2 ) line = -1;
for( ms=mwStatList; ms!=NULL; ms=ms->next ) {
if( line != ms->line ) continue;
if( file==NULL ) {
if( ms->file == NULL ) break;
continue;
}
if( ms->file == NULL ) continue;
if( !strcmp( ms->file, file ) ) break;
}
if( ms != NULL ) return ms;
if( !makenew ) return NULL;
ms = (mwStat*) malloc( sizeof(mwStat) );
if( ms == NULL ) {
if( mwFreeUp( sizeof(mwStat), 0 ) < sizeof(mwStat) ||
(ms=(mwStat*)malloc(sizeof(mwStat))) == NULL ) {
mwWrite("internal: memory low, statistics incomplete for '%s'\n", file );
return NULL;
}
}
ms->file = file;
ms->line = line;
ms->total = 0L;
ms->max = 0L;
ms->num = 0L;
ms->curr = 0L;
ms->next = mwStatList;
mwStatList = ms;
return ms;
}
static void mwStatAlloc( size_t size, const char* file, int line ) {
mwStat* ms;
/* update the module statistics */
ms = mwStatGet( file, -1, 1 );
if( ms != NULL ) {
ms->total += (long) size;
ms->curr += (long) size;
ms->num ++;
if( ms->curr > ms->max ) ms->max = ms->curr;
}
/* update the line statistics */
if( mwStatLevel > 1 && line != -1 && file ) {
ms = mwStatGet( file, line, 1 );
if( ms != NULL ) {
ms->total += (long) size;
ms->curr += (long) size;
ms->num ++;
if( ms->curr > ms->max ) ms->max = ms->curr;
}
}
}
static void mwStatFree( size_t size, const char* file, int line ) {
mwStat* ms;
/* update the module statistics */
ms = mwStatGet( file, -1, 1 );
if( ms != NULL ) ms->curr -= (long) size;
/* update the line statistics */
if( mwStatLevel > 1 && line != -1 && file ) {
ms = mwStatGet( file, line, 1 );
if( ms != NULL ) ms->curr -= (long) size;
}
}
/***********************************************************************
** Safe memory checkers
**
** Using ifdefs, implement the operating-system specific mechanism
** of identifying a piece of memory as legal to access with read
** and write priviliges. Default: return nonzero for non-NULL pointers.
***********************************************************************/
static char mwDummy( char c )
{
return c;
}
#ifndef MW_SAFEADDR
#ifdef WIN32
#define MW_SAFEADDR
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
int mwIsReadAddr( const void *p, unsigned len )
{
if( p == NULL ) return 0;
if( IsBadReadPtr(p,len) ) return 0;
return 1;
}
int mwIsSafeAddr( void *p, unsigned len )
{
/* NOTE: For some reason, under Win95 the IsBad... */
/* can return false for invalid pointers. */
if( p == NULL ) return 0;
if( IsBadReadPtr(p,len) || IsBadWritePtr(p,len) ) return 0;
return 1;
}
#endif /* WIN32 */
#endif /* MW_SAFEADDR */
#ifndef MW_SAFEADDR
#ifdef SIGSEGV
#define MW_SAFEADDR
typedef void (*mwSignalHandlerPtr)( int );
mwSignalHandlerPtr mwOldSIGSEGV = (mwSignalHandlerPtr) 0;
jmp_buf mwSIGSEGVjump;
static void mwSIGSEGV( int n );
static void mwSIGSEGV( int n )
{
n = n;
longjmp( mwSIGSEGVjump, 1 );
}
int mwIsReadAddr( const void *p, unsigned len )
{
const char *ptr;
if( p == NULL ) return 0;
if( !len ) return 1;
/* set up to catch the SIGSEGV signal */
mwOldSIGSEGV = signal( SIGSEGV, mwSIGSEGV );
if( setjmp( mwSIGSEGVjump ) )
{
signal( SIGSEGV, mwOldSIGSEGV );
return 0;
}
/* read all the bytes in the range */
ptr = (const char *)p;
ptr += len;
/* the reason for this rather strange construct is that */
/* we want to keep the number of used parameters and locals */
/* to a minimum. if we use len for a counter gcc will complain */
/* it may get clobbered by longjmp() at high warning levels. */
/* it's a harmless warning, but this way we don't have to see it. */
do
{
ptr --;
if( *ptr == 0x7C ) (void) mwDummy( (char)0 );
} while( (const void*) ptr != p );
/* remove the handler */
signal( SIGSEGV, mwOldSIGSEGV );
return 1;
}
int mwIsSafeAddr( void *p, unsigned len )
{
char *ptr;
if( p == NULL ) return 0;
if( !len ) return 1;
/* set up to catch the SIGSEGV signal */
mwOldSIGSEGV = signal( SIGSEGV, mwSIGSEGV );
if( setjmp( mwSIGSEGVjump ) )
{
signal( SIGSEGV, mwOldSIGSEGV );
return 0;
}
/* read and write-back all the bytes in the range */
ptr = (char *)p;
ptr += len;
/* the reason for this rather strange construct is that */
/* we want to keep the number of used parameters and locals */
/* to a minimum. if we use len for a counter gcc will complain */
/* it may get clobbered by longjmp() at high warning levels. */
/* it's a harmless warning, but this way we don't have to see it. */
do
{
ptr --;
*ptr = mwDummy( *ptr );
} while( (void*) ptr != p );
/* remove the handler */
signal( SIGSEGV, mwOldSIGSEGV );
return 1;
}
#endif /* SIGSEGV */
#endif /* MW_SAFEADDR */
#ifndef MW_SAFEADDR
int mwIsReadAddr( const void *p, unsigned len )
{
if( p == NULL ) return 0;
if( len == 0 ) return 1;
return 1;
}
int mwIsSafeAddr( void *p, unsigned len )
{
if( p == NULL ) return 0;
if( len == 0 ) return 1;
return 1;
}
#endif
/**********************************************************************
** Mutex handling
**********************************************************************/
#if defined(WIN32) || defined(__WIN32__)
static void mwMutexInit( void )
{
mwGlobalMutex = CreateMutex( NULL, FALSE, NULL);
return;
}
static void mwMutexTerm( void )
{
CloseHandle( mwGlobalMutex );
return;
}
static void mwMutexLock( void )
{
if( WaitForSingleObject(mwGlobalMutex, 1000 ) == WAIT_TIMEOUT )
{
mwWrite( "mwMutexLock: timed out, possible deadlock\n" );
}
return;
}
static void mwMutexUnlock( void )
{
ReleaseMutex( mwGlobalMutex );
return;
}
#endif
#if defined(MW_PTHREADS) || defined(HAVE_PTHREAD_H)
static void mwMutexInit( void )
{
pthread_mutex_init( &mwGlobalMutex, NULL );
return;
}
static void mwMutexTerm( void )
{
pthread_mutex_destroy( &mwGlobalMutex );
return;
}
static void mwMutexLock( void )
{
pthread_mutex_lock(&mwGlobalMutex);
return;
}
static void mwMutexUnlock( void )
{
pthread_mutex_unlock(&mwGlobalMutex);
return;
}
#endif
/**********************************************************************
** C++ new & delete
**********************************************************************/
#if 0 /* 980317: disabled C++ */
#ifdef __cplusplus
#ifndef MEMWATCH_NOCPP
int mwNCur = 0;
const char *mwNFile = NULL;
int mwNLine = 0;
class MemWatch {
public:
MemWatch();
~MemWatch();
};
MemWatch::MemWatch() {
if( mwInited ) return;
mwUseAtexit = 0;
mwInit();
}
MemWatch::~MemWatch() {
if( mwUseAtexit ) return;
mwTerm();
}
/*
** This global new will catch all 'new' calls where MEMWATCH is
** not active.
*/
void* operator new( unsigned size ) {
mwNCur = 0;
return mwMalloc( size, "<unknown>", 0 );
}
/*
** This is the new operator that's called when a module uses mwNew.
*/
void* operator new( unsigned size, const char *file, int line ) {
mwNCur = 0;
return mwMalloc( size, file, line );
}
/*
** This is the new operator that's called when a module uses mwNew[].
** -- hjc 07/16/02
*/
void* operator new[] ( unsigned size, const char *file, int line ) {
mwNCur = 0;
return mwMalloc( size, file, line );
}
/*
** Since this delete operator will recieve ALL delete's
** even those from within libraries, we must accept
** delete's before we've been initialized. Nor can we
** reliably check for wild free's if the mwNCur variable
** is not set.
*/
void operator delete( void *p ) {
if( p == NULL ) return;
if( !mwInited ) {
free( p );
return;
}
if( mwNCur ) {
mwFree( p, mwNFile, mwNLine );
mwNCur = 0;
return;
}
mwFree_( p );
}
void operator delete[]( void *p ) {
if( p == NULL ) return;
if( !mwInited ) {
free( p );
return;
}
if( mwNCur ) {
mwFree( p, mwNFile, mwNLine );
mwNCur = 0;
return;
}
mwFree_( p );
}
#endif /* MEMWATCH_NOCPP */
#endif /* __cplusplus */
#endif /* 980317: disabled C++ */
/* MEMWATCH.C */
|
100siddhartha-blacc
|
memwatch.c
|
C
|
mit
| 75,970
|
#include "parse.h"
#include "check.h"
#include "operator.h"
#include "globals.h"
static
void DumpRule(FILE* Handle, TRule* Rule)
{
fprintf(Handle, " -> ");
SymbolListDump(Handle, Rule->Symbols, " ");
fprintf(Handle, "\n");
}
/* CheckLR0RuleDup() - check for duplicate rules.
*
* We already checked for duplicate rules in CommonLeft(),
* but operator abbreviations add an extra level of complexity
* that gets handled here.
*
* main()
* ...
* CheckLR0Rules()
* CheckLR0Rule()
* CheckLR0RuleDup()
* ComputeAllLR0()
* ...
*/
static
void CheckLR0RuleDup(TSymbol* NonTerm, TRule* RuleA, TRule* RuleB)
{
int NSymA, NSymB, iProdItem;
TSymbol* SymA;
TSymbol* SymB;
SYMBOLS ListA, ListB, ListIntersect;
NSymA = RuleItemCount(RuleA);
NSymB = RuleItemCount(RuleB);
/* if both rhs are same length, might be dup */
if(NSymA == NSymB)
{
printf("Check for rule dups between:\n");
DumpRule(stdout, RuleA);
DumpRule(stdout, RuleB);
for(iProdItem=0; iProdItem < NSymA; ++iProdItem)
{
SymA = SymbolListGet(RuleA->Symbols, iProdItem);
SymB = SymbolListGet(RuleB->Symbols, iProdItem);
if(!SymbolIsEqual(SymA, SymB) && !(SymA->OpAbbrev || SymB->OpAbbrev))
break;
else if(SymbolIsEqual(SymA,SymB))
continue;
/* now they are not equal, and one or both is an operator abbreviation */
/* embedded actions not allowed; handled elsewhere */
assert(!(SymbolIsAction(SymA) || SymbolIsAction(SymB)));
printf("operator abbrev involved!\n");
ListA = SymA->OpAbbrev ? SymbolListCopy(NULL, SymA->OpAbbrev) : SymbolListAdd(NULL, SymA);
ListB = SymB->OpAbbrev ? SymbolListCopy(NULL, SymB->OpAbbrev) : SymbolListAdd(NULL, SymB);
ListIntersect = SymbolListIntersect(ListA, ListB);
if(ListIntersect)
{
/* simple duplicates were handled elsewhere */
assert(!SymbolIsEqual(SymA,SymB));
ErrorPrologue(ERROR_CLASH_IN_OP_ABBREV);
Error("These two rules of '%s' intersect:\n", SymbolStr(NonTerm));
DumpRule(stderr, RuleA);
DumpRule(stderr, RuleB);
Error("because the operator abbreviator");
if(SymA->OpAbbrev)
{
Error("%s '%s'", SymB->OpAbbrev?"s":"", SymbolStr(SymA));
if(SymB->OpAbbrev)
Error(" and %s both contain ", SymbolStr(SymB));
else
Error(" contains ");
}
else if(SymB->OpAbbrev)
Error(" '%s' contains ", SymbolStr(SymB));
Error("%s.\n", SymbolStr(SymbolListGet(ListIntersect, 0)));
ErrorEpilog(-1);
SymbolListDestroy(ListA);
SymbolListDestroy(ListB);
if(ListIntersect)
SymbolListDestroy(ListIntersect);
}
else if(!SymbolIsEqual(SymA,SymB))
break;
/* else, looks like a duplicate so far, so keep going */
}
}
}
#if 0
/* CheckOpAbbrev()
*
* We hit a nonterminal in an LR(0) rule that was not declared as
* an operand. Here, we see if it could not possibly be an
* operator abbreviation. If it can't be, then we fail with an
* error message. If it could be an operator abbreviation, then
* we return the list of operators that this nonterminal represents.
*/
static
SYMBOLS CheckOpAbbrev(TToken Token, TSymbol* NonTerm)
{
int iRule, NRules, iSymbol;
TRule** Rover;
TRule* Rule;
TSymbol* Symbol;
SYMBOLS Result = NULL;
char Buffer[1024];
DumpVerbose("CheckOpAbbrev('%s')\n", SymbolStr(NonTerm));
NRules = NonTerm->NRules;
for(iRule=0; iRule < NRules; ++iRule)
{
Rule = NonTerm->Rules[iRule];
for(iSymbol=0; (Symbol=SymbolListGet(Rule->Symbols, iSymbol)) != NULL; ++iSymbol)
{
if(SymbolIsAction(Symbol))
{
sprintf(Buffer, "its production rules include an action, not just operators.");
break;
}
else if(SymbolGetBit(Symbol, TERMINAL) == FALSE)
{
sprintf(Buffer, "its production rules include a nonterminal ('%s'), not just operators.",
SymbolStr(Symbol));
break;
}
else if(iSymbol == 1)
{
sprintf(Buffer, "at least one of its rules contains more than one terminal.\n"
"%s -> %s %s %s\n",
SymbolStr(NonTerm), SymbolListGet(Rule->Symbols, 0), Symbol,
SymbolListCount(Rule->Symbols) > 1 ? "..." : "");
break;
}
else
Result = SymbolListAdd(Result, Symbol);
}
if(iSymbol < SymbolListCount(Rule->Symbols))
break;
}
if(iRule < NRules)
SyntaxError(ERROR_BAD_OP_ABBREV, Token,
"%s was not declared as an operand, so I thought it might be an operator abbreviation. However, \n%s",
SymbolStr(NonTerm), Buffer);
if(Globals.Dump && Globals.Verbose)
{
if(Result)
{
Dump(" returns ");
SymbolListDump(stdout, Result, " ");
Dump("\n");
}
else
Dump(" returns NULL\n");
}
return Result;
}
/* CheckLR0Rule() - check a single rule of a LR0 nonterminal.
*/
static
void CheckLR0Rule(TSymbol* NonTerm, TRule* Rule)
{
int iProdItem, NProdItems, iOperator, OpType;
TSymbol* Symbol;
TOperator* Operator;
char Pattern[MAX_OPERATOR_PATTERN+1];
char* PatRover = Pattern;
char* QMark;
NProdItems = SymbolListCount(Rule->Symbols);
/* Make sure symbols in rule are all either
* operators or operands.
*/
for(iProdItem=0; iProdItem < NProdItems; ++iProdItem)
{
Symbol = SymbolListGet(Rule->Symbols, iProdItem);
if(SymbolIsAction(Symbol))
{
if(iProdItem != (NProdItems-1))
{
ErrorPrologue(ERROR_NO_EMBEDDED_ACTION);
Error("Embedded actions not allowed in operator precedence rule:\n%s", SymbolStr(NonTerm));
DumpRule(stderr, Rule);
ErrorEpilog(-1);
}
else
--NProdItems; /* revise to reflect "real" count */
}
else if(Symbol->Operand)
{
*PatRover++ = 'X';
assert(PatRover - Pattern < MAX_OPERATOR_PATTERN);
}
else if((Operator=OperatorFindOpSym(NULL, Symbol)) != NULL)
*PatRover++ = '.';
else if(SymbolGetBit(Symbol, SYM_TERMINAL))
SyntaxError(ERROR_NOT_OPERATOR_OR_OPERAND, Rule->Tokens[iProdItem],
"'%s' is a terminal used by '%s' but was not declared as an operator or operand.",
SymbolStr(Symbol), SymbolStr(NonTerm)
);
/* by now, we know it's a nonterminal not declared as operator or operand */
else
*PatRover++ = '?'; /* remember it as possible error or operator abbreviation */
}
*PatRover = '\0';
Symbol = NULL; /* we'll set it to operator abbreviation, if any */
/* were there one or more undeclared nonterminals? */
QMark = strchr(Pattern, '?');
if(QMark)
{
SYMBOLS Operators;
Symbol = SymbolListGet(Rule->Symbols, QMark-Pattern);
/* is it potentially legal if nonterminal is an operator abbreviation? */
if(!strcmp(Pattern, "X?"))
OpType = OP_PRE_UNARY;
else if(!strcmp(Pattern, "?X"))
OpType = OP_POST_UNARY;
else if(!strcmp(Pattern, "X?X"))
OpType = OP_BINARY;
else
OpType = OP_UNKNOWN;
fprintf(stdout, "QMark pattern='%s'\n", Pattern);
if(OpType == OP_UNKNOWN)
SyntaxError(ERROR_NOT_OPERATOR_OR_OPERAND, Rule->Tokens[QMark-Pattern],
"'%s' is a nonterminal used by '%s' but was not declared as an operator or operand.\n"
"The rule isn't the right form for '%s' to be an operator abbreviation, either.\n",
SymbolStr(Symbol), SymbolStr(NonTerm), SymbolStr(Symbol)
);
*QMark = '.'; /* assume it's going to be a legal operator */
/* because we think there's an operator abbreviation involved,
* have to make sure all the possibilities match declared operators.
*/
Symbol->OpAbbrev = Operators = CheckOpAbbrev(Rule->Tokens[QMark-Pattern], Symbol);
fprintf(stdout, "'%s' is an operator abbreviation\n", SymbolStr(Symbol));
}
fprintf(stdout, "pattern='%s'\n", Pattern);
/* OK, it's all operators and operands, but does it match an operator declaration? */
if(strcmp(Pattern, "X"))
{
Operator = NULL;
for(iOperator=0; (Operator=OperatorGet(iOperator)) != NULL; ++iOperator)
{
// fprintf(stdout, "Compare op '%s' to '%s'\n", Pattern, Operator->Pattern);
if(!strcmp(Pattern, Operator->Pattern))
/* ??? TODO: make sure operators actually match */
break;
}
if(Operator == NULL)
{
ErrorPrologue(ERROR_NO_MATCHING_OPERATOR_PATTERN);
Error("This rule: %s ", SymbolStr(NonTerm));
DumpRule(stderr, Rule);
Error("\ndoesn't seem to correspond to any of operators you declared.\n");
ErrorEpilog(-1);
}
}
}
#if 0
else if(
{
}
else if(CheckOpAbbrev(Symbol, Buffer))
*PatRover++ = '.';
else
{
*Rover= '\0';
SyntaxError(ERROR_NOT_OPERATOR_OR_OPERAND, Rule->Tokens[iProdItem],
"'%s': was not declared as an operator or operand and\ndoesn't appear to be a set of unary or binary operators.",
SymbolStr(Symbol)
);
}
#endif
/* CheckLR0Rules() - make sure expression rules are legal.
*
* Note that this has the important side-effect of setting the
* IsOpAbbrev flag in nonterminals that appear to be legal operator
* abbreviations.
*/
void CheckLR0Rules(void)
{
SymIt NonTerm;
int NRules, iRule, jRule;
Dump("CheckLR0Rules()\n");
/* for each bottom-up nonterminal */
NonTerm = SymItNew(Globals.NonTerms);
while(SymbolIterate(&NonTerm))
if(NonTerm.Symbol->OperatorTrigger)
{
NRules = NonTerm.Symbol->NRules;
for(iRule = 0; iRule < NRules; ++iRule)
CheckLR0Rule(NonTerm.Symbol, NonTerm.Symbol->Rules[iRule]);
}
/* now we've identified operator abbreviations, so look for duplicate rules */
NonTerm = SymItNew(Globals.NonTerms);
while(SymbolIterate(&NonTerm))
if(NonTerm.Symbol->OperatorTrigger)
{
NRules = NonTerm.Symbol->NRules;
for(iRule = 0; iRule < (NRules-1); ++iRule)
for(jRule = iRule+1; jRule < NRules; ++jRule)
CheckLR0RuleDup(NonTerm.Symbol, NonTerm.Symbol->Rules[iRule], NonTerm.Symbol->Rules[jRule]);
}
Dump("CheckLR0Rules() done\n");
}
#endif
/* GetSingles() - list of single non-terminals this nonterminal can produce directly
*
* Algorithm (roughly) from Coco book, pp.150-151.
*/
static
SYMBOLS GetSingles(TSymbol* Left)
{
SYMBOLS Result;
TRule** Rover;
Result = SymbolListCreate();
Rover = Left->Rules;
if(Rover)for(; *Rover; ++Rover)
{
TRule* Rule = *Rover;
SymIt ProdItem = SymItNew(Rule->Symbols);
while(SymbolIterate(&ProdItem))
if(!SymbolIsAction(ProdItem.Symbol))
{
int RhsNullable;
/* can't derive a single non-terminal if we have to emit a terminal */
if(SymbolGetBit(ProdItem.Symbol, SYM_TERMINAL))
break;
/* figure out if everything to the right is nullable */
RhsNullable = RuleNullable(Rule, ProdItem.Index);
/* We're examining a nonterminal from the rhs. All symbols to the
* left (if any) are nullable. So, if all the symbols to the right
* are also nullable, then we can derive a string containing only
* this nonterminal.
*/
if(RhsNullable)
SymbolListAddUnique(Result, ProdItem.Symbol);
/* if it's not nullable, then no point in looking further to the right
*/
if(!ProdItem.Symbol->Nullable)
break;
}
}
if(Globals.Dump && Globals.Verbose)
{
Dump("GetSingles('%s') = ", SymbolStr(Left));
SymbolListDump(stdout, Result, ", ");
Dump("\n");
}
return Result;
}
/* CheckCircularity() - detect any cycles in the graph.
*
*/
int CheckCircularity(void)
{
SYMBOLS Left=NULL, Right=NULL;
SymIt NonTerm;
int Changed;
int ErrorCount = 0;
Dump("CheckCircularity()\n");
/* for each nonterminal */
NonTerm = SymItNew(Globals.NonTerms);
while(SymbolIterate(&NonTerm))
if(!SymbolIsAction(NonTerm.Symbol))
{
SYMBOLS Singles;
SymIt Single;
/* fetch all the single nonterminals it can directly derive */
Singles = GetSingles(NonTerm.Symbol);
/* for each of the right-hand-side single nonterminals */
Single = SymItNew(Singles);
while(SymbolIterate(&Single))
{
/* Add them to the list of graph nodes. Conceptually,
* we are recording the fact that 'Left' can derive a
* string that contains only a 'Right'.
*/
Left = SymbolListAdd(Left, NonTerm.Symbol);
Right = SymbolListAdd(Right, Single.Symbol);
}
SymbolListDestroy(Singles);
}
/* remove edges from the graph that aren't part of any cycle */
do {
SymIt GraphNode;
Changed = FALSE;
GraphNode = SymItNew(Left);
while(SymbolIterate(&GraphNode))
{
TSymbol* LeftSym = GraphNode.Symbol;
TSymbol* RightSym = SymbolListGet(Right, GraphNode.Index);
/* So, we know that 'LeftSym' can derive a 'RightSym'.
* But, if nothing derives a 'LeftSym', or 'RightSym'
* derives nothing, then this connection can't be part of
* any cycle, so remove it from graph.
*/
if(!SymbolListContains(Right, LeftSym) || !SymbolListContains(Left, RightSym))
{
SymbolListDelete(Left, GraphNode.Index);
SymbolListDelete(Right, GraphNode.Index);
--GraphNode.Index;
Changed = TRUE;
}
}
} while(Changed);
/* if graph is not empty, then there is one or more circular symbols */
if(SymbolListCount(Left) > 0)
{
/* TODO: need a nice description of how they are circular!
*
* do while FoundNewCycle
* for each symbol in Left
* find biggest cycle it is part of
* if cycle not in list of previously found cycles
* add cycle to list
* print out cycle
*/
fprintf(stderr, "Circular symbols: \n");
SymbolListDump(stderr, Left, ", ");
fprintf(stderr, "\n");
SymbolListDump(stderr, Right, ", ");
fprintf(stderr, "\n");
++ErrorCount;
}
SymbolListDestroy(Left);
SymbolListDestroy(Right);
Dump("CheckCircularity() returns %d\n", ErrorCount);
return ErrorCount;
}
/* CheckCompleteness() - Make sure all non-terminals have a rule.
*
*/
int CheckCompleteness(void)
{
TRule** Rover;
int iNonTerm, jNonTerm;
int NNonTerms;
int ErrorCount = 0;
NNonTerms = SymbolListCount(Globals.NonTerms);
for(iNonTerm = 0; iNonTerm < NNonTerms; ++iNonTerm)
{
TSymbol* Undefined;
Undefined = SymbolListGet(Globals.NonTerms, iNonTerm);
if(!SymbolIsAction(Undefined) && Undefined->Rules == NULL)
{
++ErrorCount;
fprintf(stderr,
"Undefined non-terminal '%.*s'. It was referenced:\n",
Undefined->Name.TextLen,
Undefined->Name.Text);
for(jNonTerm=0; jNonTerm < NNonTerms; ++jNonTerm)
{
TSymbol* Temp = SymbolListGet(Globals.NonTerms, jNonTerm);
/* for each production of this non-terminal */
Rover = Temp->Rules;
if(Rover)for(; *Rover; ++Rover)
{
int iSymbol, NSymbols;
TRule* Rule = *Rover;
assert(Rule != NULL);
NSymbols = SymbolListCount(Rule->Symbols);
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
{
TSymbol* Rhs = SymbolListGet(Rule->Symbols, iSymbol);
assert(Rhs != NULL);
if(Rhs == Undefined)
{
TContext Context;
if(Rule->Tokens)
{
Context = InputGetContext(Rule->Tokens[iSymbol].Text);
fprintf(stderr, " on Line %d: by '%.*s'\n '%.*s'\n",
Context.LineNumber,
Temp->Name.TextLen, Temp->Name.Text,
Context.LineLen, Context.LineStart);
}
else
fprintf(stderr, " by an internally generated rule.\n");
}
}
}
}
}
}
return ErrorCount;
}
/* CheckReachability() - are all non-terminals reachable from start symbol?
*/
static
void MarkReached(SYMBOLS Reached, TSymbol* NonTerm)
{
TRule** Rover;
assert(NonTerm != NULL);
/* if this symbol not already marked as "reached" */
if(!SymbolIsAction(NonTerm) && !SymbolListContains(Reached, NonTerm))
{
assert(SymbolGetBit(NonTerm, SYM_TERMINAL) == FALSE);
/* mark this symbol as "reached" */
SymbolListAdd(Reached, NonTerm);
/* for each production of this non-terminal */
Rover = NonTerm->Rules;
if(Rover)for(; *Rover; ++Rover)
{
int iSymbol, NSymbols;
TRule* Rule = *Rover;
assert(Rule != NULL);
/* for each symbol of this production */
NSymbols = SymbolListCount(Rule->Symbols);
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
{
TSymbol* Rhs = SymbolListGet(Rule->Symbols, iSymbol);
assert(Rhs != NULL);
/* mark as "reached" each non-terminal in the production */
if(!SymbolIsTerminal(Rhs))
MarkReached(Reached, Rhs);
}
}
}
}
/* CheckReachability() - are all symbols reachable from start symbol?
*
* Note that a single typo for a top-level non-terminal can create an
* unreadable cascade, as some/all the children of that single typo then
* get listed as non-reachable. We really want a way to point out the real
* root of the problem.
*
* Note that there's no guarantee of a single "root" of the orphaned nodes.
* For example, suppose we forgot to make A reachable in a grammar that contains:
* A : B ';' ;
* B : ident | A ;
* When there's a cycle, there's no easy way to programmatically guess whether
* it was a failure to mention A, B, or both that is the "real" user mistake.
* But a more normal problem is this:
* program : module TK_END ;
* Module : // all the rest of the productions!
* Here, a single typo makes nearly all the non-terminals unreachable, producing
* a huge list of "problems", when we really just want to point out that
* 'Module' is the cause for the rest of them being unreachable.
*
* Our algorithm goes as follows. First, make a list of all the non-terminals
* not reached. For each non-terminal not reached, make a list of all the
* other not reached symbols it can reach. Sort the non-reached non-terminals
* by how many other not-reached symbols they reach, largest first. Print
* the first not-reached non-terminal in this list. (if we are being verbose,
* print all the non-reached non-terminals it reaches indented beneath it)
* Now remove that non-terminal and all it reached from the unreached list
* and move to the next one (but only print it if it is still in the unreached
* list).
*
* Whew, this may be the most CPU ever devoted to a single error message!
*
*/
static
int CompareSymLists(const void* A, const void* B)
{
SYMBOLS* a;
SYMBOLS* b;
a = (SYMBOLS*)A;
b = (SYMBOLS*)B;
return SymbolListCount(*b) - SymbolListCount(*a);
}
void CheckReachability(void)
{
TSymbol* Symbol;
int iNonTerm, NNonTerms, NUnreached;
SYMBOLS Reached, Unreached;
int ErrorCount = 0;
NNonTerms = SymbolListCount(Globals.NonTerms);
assert(NNonTerms > 0);
Reached = SymbolListCreate();
Unreached = SymbolListCreate();
MarkReached(Reached, SymbolStart());
/* make the complementary list: those not reached */
for(iNonTerm = 0; iNonTerm < NNonTerms; ++iNonTerm)
{
Symbol = SymbolListGet(Globals.NonTerms, iNonTerm);
if(!SymbolListContains(Reached, Symbol))
SymbolListAdd(Unreached, Symbol);
}
/* if there were symbols not reached */
NUnreached = SymbolListCount(Unreached);
if(NUnreached > 0)
{
SYMBOLS* Sorted = calloc(NUnreached, sizeof(SYMBOLS));
fprintf(stderr, "Out of %d non-terminals, %d are reachable, %d are unreachable:\n",
SymbolListCountSig(Globals.NonTerms),
SymbolListCountSig(Reached),
SymbolListCountSig(Unreached)
);
/* build array of symbols each unreached symbol can reach */
for(iNonTerm = 0; iNonTerm < NUnreached; ++iNonTerm)
{
SYMBOLS Temp;
TSymbol* ThisUnreached = SymbolListGet(Unreached, iNonTerm);
Sorted[iNonTerm] = SymbolListCreate();
MarkReached(Sorted[iNonTerm], ThisUnreached);
/* retain only symbols on the unreached list */
Temp = SymbolListIntersect(Sorted[iNonTerm], Unreached);
SymbolListDestroy(Sorted[iNonTerm]);
Sorted[iNonTerm] = Temp;
}
/* now sort the array by size */
qsort(Sorted, NUnreached, sizeof(SYMBOLS), CompareSymLists);
/* for each unreached symbol */
for(iNonTerm=0; iNonTerm < NUnreached; ++iNonTerm)
{
Symbol = SymbolListGet(Sorted[iNonTerm], 0);
/* if we haven't already printed out this unreachable symbol */
if(SymbolListContains(Unreached, Symbol))
{
int iSymbol, NSymbols;
/* print out unreachable symbol, with all the unreachables it
* reaches indented underneath it.
*/
NSymbols = SymbolListCount(Sorted[iNonTerm]);
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
{
Symbol = SymbolListGet(Sorted[iNonTerm], iSymbol);
fprintf(stderr, "%s'%.*s'\n", iSymbol ? " " : "",
Symbol->Name.TextLen, Symbol->Name.Text);
/* remove printed symbol from further display */
SymbolListRemove(Unreached, Symbol);
}
}
SymbolListDestroy(Sorted[iNonTerm]);
}
free(Sorted);
}
SymbolListDestroy(Unreached);
SymbolListDestroy(Reached);
if(ErrorCount)
Exit(-1, ERROR_UNREACHABLE_NONTERMINAL);
}
static
int Terminates(SYMBOLS TerminateList, SYMBOLS Visited, TSymbol* Symbol)
{
int Result = FALSE;
if(SymbolIsTerminal(Symbol)) /* a terminal terminates, so there! */
Result = TRUE;
else if(SymbolIsNullable(Symbol)) /* deriving empty string counts as termination */
Result = TRUE;
else if(!SymbolIsTerminal(Symbol))
{
/* if it's a cycle */
if(SymbolListContains(Visited, Symbol))
Result = FALSE;
/* else, if already known to terminate */
else if(SymbolListContains(TerminateList, Symbol))
Result = TRUE;
/* else, have to check each rule, one by one */
else
{
TRule** Rover;
TRule* Rule;
SymbolListAdd(Visited, Symbol);
Rover = Symbol->Rules;
if(Rover)for(; *Rover; ++Rover)
{
int Terminated, iItem, NItems;
Rule = *Rover;
NItems = SymbolListCount(Rule->Symbols);
Terminated = TRUE;
for(iItem = 0; iItem < NItems; ++iItem)
{
TSymbol* Item = SymbolListGet(Rule->Symbols, iItem);
if(!Terminates(TerminateList, Visited, Item))
{
Terminated = FALSE;
break;
}
}
if(Terminated)
{
Result = TRUE;
break;
}
}
}
}
else
assert(FALSE);
return Result;
}
/* CheckTermination() - verify that all nonterminals can terminate.
*
* Confirm that all nonterminals can produce either epsilon or a string
* containing only terminals.
*
* Algorithm: mark nonterminals that are nullable or have a rule containing
* only terminals or already marked nonterminals. Repeat until no more can
* be marked. Any nonterminal not marked will not terminate.
*
* Unless verbosity was requested, we want to avoid reporting nontermination
* caused by some other nonterminating symbol. Consider this grammar:
*
* S : A ;
* A : A B ;
*
* A clearly does not terminate. The sole reason S does not terminate is
* because A does not terminate. Hence, we would like to not (by default)
* report S as a nonterminating symbol because that will distract attention
* from the root cause.
*/
static
int IsInCycle(SYMBOLS List, TSymbol* Target)
{
int Result = FALSE; /* assume Symbol is not part of a cycle */
RuleIt Rhs;
SYMBOLS Used;
int iUsed;
Used = SymbolListAdd(NULL, Target);
for(iUsed = 0; iUsed < SymbolListCount(Used) && !Result; ++iUsed)
for(Rhs = RuleItNew(SymbolListGet(Used, iUsed)); RuleIterate(&Rhs); ) /* iterate over RHS of next symbol */
if(Rhs.ProdItem == Target)
{
Result = TRUE;
break;
}
else if(SymbolListContains(List, Rhs.ProdItem))
Used = SymbolListAddUnique(Used, Rhs.ProdItem);
SymbolListDestroy(Used);
return Result;
}
int CheckTermination(void)
{
int NNonTerms;
SYMBOLS TerminateList = NULL;
SYMBOLS NoTerminateList = NULL;
int FoundMore;
int iLoop, MaxLoops;
int ErrorCount = 0;
SymIt NonTerm, Bad;
NNonTerms = SymbolListCount(Globals.NonTerms);
TerminateList = SymbolListCreate();
NoTerminateList = SymbolListCreate();
MaxLoops = NNonTerms * NNonTerms;
FoundMore = TRUE;
for(iLoop = 0; iLoop <= MaxLoops && FoundMore; ++iLoop)
{
NonTerm = SymItNew(Globals.NonTerms);
FoundMore = FALSE;
while(SymbolIterate(&NonTerm))
{
SYMBOLS Visited;
if(!SymbolListContains(TerminateList, NonTerm.Symbol))
{
assert(!SymbolIsTerminal(NonTerm.Symbol));
Visited = SymbolListCreate();
if(Terminates(TerminateList, Visited, NonTerm.Symbol))
{
TerminateList = SymbolListAdd(TerminateList, NonTerm.Symbol);
FoundMore = TRUE;
}
SymbolListDestroy(Visited);
}
}
}
/* must have completed within MaxLoops or it's a bug */
assert(FoundMore == FALSE);
/* if not all symbols terminate */
if(NNonTerms > SymbolListCount(TerminateList))
{
fprintf(stderr, "Don't all terminate.\n");
/* form list of symbols that don't terminate */
NonTerm = SymItNew(Globals.NonTerms);
while(SymbolIterate(&NonTerm))
{
if(!SymbolListContains(TerminateList, NonTerm.Symbol))
NoTerminateList = SymbolListAdd(NoTerminateList, NonTerm.Symbol);
}
Bad = SymItNew(NoTerminateList);
/* now report on (possibly) redacted list */
while(SymbolIterate(&Bad))
{
// if(ShouldReportCycle(NonterminateList, Symbol))
// if(!SymbolListContains(TerminateList, Bad.Symbol))
if(IsInCycle(NoTerminateList, Bad.Symbol))
{
++ErrorCount;
fprintf(stderr, "Non-terminal %s will not terminate.\n",
SymbolStr(Bad.Symbol));
}
}
assert(ErrorCount > 0);
}
SymbolListDestroy(NoTerminateList);
SymbolListDestroy(TerminateList);
return ErrorCount;
}
/* CheckOpsUsed() - warn if any operator/operands not actually used.
*
*/
void CheckOpsUsed(void)
{
int NOperators, iOperator, iSymbol;
SYMBOLS NotUsed;
TOperator* Operator;
TSymbol* Symbol;
NotUsed = NULL;
NOperators = OperatorCount();
for(iOperator = 0; iOperator < NOperators; ++iOperator)
{
Operator = OperatorGet(iOperator);
for(iSymbol = 0; iSymbol < SymbolListCount(Operator->List); ++iSymbol)
{
Symbol = SymbolListGet(Operator->List, iSymbol);
if(Symbol && !Symbol->UsedInRule)
{
NotUsed = SymbolListAdd(NotUsed, Symbol);
}
}
}
if(NotUsed)
{
fprintf(stderr, "%d operators not used. ", SymbolListCount(NotUsed));
fprintf(stderr, "Operator%s declared but not used:\n ",
(SymbolListCount(NotUsed) > 1) ? "s" : "");
SymbolListDump(stderr,NotUsed, ", ");
fprintf(stderr, "\n");
SymbolListDestroy(NotUsed);
}
}
/* CheckFirstFirstClash() - find two rules with intersecting FIRST sets.
*
* This would be simple except we want to also detect FIRST/FIRST clashes
* that would appear if we left-factored common prefixes.
*
* Consider this C99 fragment, where declaration_list is nullable:
* compound_statement
* : '{' '}'
* | '{' statement_list '}'
* | '{' declaration_list '}'
* | '{' declaration_list statement_list '}'
* ;
* We do NOT want to complain that all the rules start with '{',
* since that can be solved by left-factoring. However, because
* declaration_list is nullable, the first and third rules contain
* a FIRST/FIRST clash that would only appear AFTER left-factoring.
*/
/* ReportFirstFirstExample() - show why 'FirstClash' is in FIRST('Sym').
*
*/
static
void ReportFirstFirstExample(TSymbol* Sym, TSymbol* FirstClash)
{
static int ForExample = 0;
int iRule, NRules;
TRule* Rule;
TSymbol* FirstSym = NULL;
TSymbol* Temp = NULL;
int Intro;
int iProdItem, jProdItem, BestRule, MoreChoices;
for(Intro=FALSE;;)
{
MoreChoices = FALSE;
BestRule = -1;
#if 0
/* prefer simplest explanation: if there's a rule that starts with
* the terminal 'FirstClash', then that will be easiest for the user
* to understand.
*/
for(iRule=0; iRule<Sym->NRules; ++iRule)
{
Rule = Sym->Rules[iRule];
FirstSym = SymbolListGet(Rule->Symbols, 0);
if(FirstSym == FirstClash)
{
if(!Intro)
{
fprintf(stdout, "%s:\n %s", ForExample?"and":"For example", SymbolStr(Sym));
Intro = ForExample = TRUE;
}
fprintf(stdout, " -> %s\n", SymbolStr(FirstClash));
/* we explained it; we're done */
return;
}
}
#endif
/* we want to use the shortest example (nonterm closest to beginning of a rule) */
for(iProdItem = 0; iProdItem >= 0; ++iProdItem)
{
/* look for symbol that is or can start with FirstClash */
NRules = RuleCount(Sym);
for(iRule = 0; iRule < NRules; ++iRule)
{
int PrefixNullable;
Rule = Sym->Rules[iRule];
/* if rule too short, skip it */
if(SymbolListCount(Rule->Symbols) <= iProdItem)
continue;
PrefixNullable = TRUE;
for(jProdItem=0; jProdItem < iProdItem &&(Temp=SymbolListGet(Rule->Symbols, jProdItem)) != NULL && SymbolIsNullable(Temp); ++jProdItem)
if((Temp=SymbolListGet(Rule->Symbols, jProdItem)) != NULL && !SymbolIsNullable(Temp))
{
PrefixNullable = FALSE;
break;
}
if(!PrefixNullable)
continue;
MoreChoices = TRUE;
FirstSym = SymbolListGet(Rule->Symbols, iProdItem);
assert(FirstSym != NULL);
/* if left-recursive rule, avoid infinite loop */
if(iProdItem == 0 && SymbolIsEqual(FirstSym, Sym))
continue;
if(SymbolIsEqual(FirstSym, FirstClash)) /* bingo: found (hopefully) shortest path to our terminal */
{
BestRule = iRule;
break; /* won't find anything better! */
}
if(SymbolIsTerminal(FirstSym) == FALSE && SymbolListContains(FirstSym->First, FirstClash))
BestRule = iRule; /* but might find a better one */
}
if(BestRule != -1)
{
int NullCount = 0;
SYMBOLS Nullables = NULL;
Rule = Sym->Rules[BestRule];
FirstSym = SymbolListGet(Rule->Symbols, iProdItem);
assert(FirstSym != NULL);
if(!Intro)
{
fprintf(stdout, "%s:\n %s ->", ForExample?"and":"For example", SymbolStr(Sym));
Intro = ForExample = TRUE;
}
else
fprintf(stdout, " %s ->", SymbolStr(Sym));
for(jProdItem=0; jProdItem <= iProdItem; ++jProdItem)
{
Temp = SymbolListGet(Rule->Symbols, jProdItem);
if(Temp->Nullable && jProdItem < iProdItem)
Nullables = SymbolListAdd(Nullables, Temp);
fprintf(stdout, " %s", SymbolStr(Temp));
}
fprintf(stdout, "%s", jProdItem < (SymbolListCount(Rule->Symbols)-1)?" ...":"");
NullCount = SymbolListCount(Nullables);
if(NullCount)
{
fprintf(stdout, " (");
SymbolListDump(stdout, Nullables, ",and");
fprintf(stdout, " %s nullable)", (NullCount>1) ? "are all" : "is");
}
fprintf(stdout, "\n");
if(FirstSym == FirstClash)
return;
Sym = FirstSym;
MoreChoices = FALSE;
break;
}
}
}
}
/* ReportSkipIrrelevant() - report and skip irrelevant nonterminals.
*
* By "irrelevant", I mean that they are nullable and not the source
* of the FIRST/FIRST clash.
*/
SYMBOLS ReportSkipIrrelevant(SYMBOLS Irrelevant, TRule* Rule, TSymbol**Sym, int iProdItem, SYMBOLS Clash)
{
SYMBOLS MoreIntersect;
MoreIntersect = SymbolListIntersect((*Sym)->First, Clash);
while(MoreIntersect == NULL)
{
assert(SymbolIsNullable(*Sym)); /* something's bad wrong if it's not nullable */
++iProdItem; /* move to next RHS symbol */
fprintf(stdout, "'%s' is nullable ", SymbolStr(*Sym));
*Sym = SymbolListGet(Rule->Symbols, iProdItem);
assert(*Sym != NULL);
MoreIntersect = SymbolListIntersect((*Sym)->First, Clash);
}
SymbolListAddList(&Irrelevant, MoreIntersect);
SymbolListDestroy(MoreIntersect);
return Irrelevant;
}
/* ReportFirstFirstClash() - turn rule conflict into intelligible message for user.
*/
static
void ReportFirstFirstClash(TSymbol* Symbol, TRule* RuleA, TRule* RuleB, int iProdItem, SYMBOLS Clash)
{
int ClashCount = SymbolListCount(Clash);
TSymbol* SymA = SymbolListGet(RuleA->Symbols, iProdItem);
TSymbol* SymB = SymbolListGet(RuleB->Symbols, iProdItem);
TSymbol* NonTerm = NULL;
TSymbol* FirstClash = SymbolListGet(Clash, 0);
SYMBOLS Irrelevant = NULL;
/* Show the two rules that conflict */
fprintf(stdout, "Can't choose between two rules of '%s'\n", SymbolStr(Symbol));
DumpRule(stdout, RuleA);
DumpRule(stdout, RuleB);
/* point out the common left prefix that is not a problem */
if(iProdItem)
{
int iSym;
fprintf(stdout, "Notice that after common left prefix of: ");
for(iSym = 0; iSym < iProdItem; ++iSym)
fprintf(stdout, " %s", SymbolStr(SymbolListGet(RuleA->Symbols, iSym)));
fprintf(stdout, ",\n");
}
/* report&skip any nullable non-terminals that are irrelevant */
Irrelevant = ReportSkipIrrelevant(Irrelevant, RuleA, &SymA, iProdItem, Clash);
Irrelevant = ReportSkipIrrelevant(Irrelevant, RuleB, &SymB, iProdItem, Clash);
if(Irrelevant)
{
fprintf(stdout, "\n");
SymbolListDestroy(Irrelevant);
}
if(SymbolIsTerminal(SymA) == FALSE)
NonTerm = SymA;
else if(SymbolIsTerminal(SymB) == FALSE)
NonTerm = SymB;
else
NonTerm = NULL;
/* now detail how the non-terminal(s) produce a clashing symbol */
if(SymbolIsEqual(SymA,SymB))
{
}
else if(NonTerm)
{
if(SymbolIsTerminal(SymA) == FALSE && SymbolIsTerminal(SymB) == FALSE)
fprintf(stdout, "Both '%s' and '%s' can start with ",
SymbolStr(SymA), SymbolStr(SymB));
else
fprintf(stdout, "'%s' can start with ", SymbolStr(NonTerm));
if(ClashCount == 1)
fprintf(stdout, "%s", SymbolStr(FirstClash));
else if(ClashCount == 2)
fprintf(stdout, "either %s or %s", SymbolStr(FirstClash), SymbolStr(SymbolListGet(Clash, 1)));
else
{
fprintf(stdout, "any of: ");
SymbolListDump(stdout, Clash, ", ");
}
fprintf(stdout, ". ");
if(SymbolIsTerminal(SymA) == FALSE)
ReportFirstFirstExample(SymA, FirstClash);
if(SymbolIsTerminal(SymB) == FALSE)
ReportFirstFirstExample(SymB, FirstClash);
}
fflush(stdout);
exit(99);
}
static
void CheckEpsilonClash(TSymbol* NonTerm, TRule* Rule, TRule* Other, int PrefixLen)
{
int NullableSuffix = TRUE;
int iProdItem, NProdItems;
TSymbol* Symbol;
for(iProdItem = PrefixLen; (Symbol=SymbolListGet(Rule->Symbols, iProdItem))!=NULL; ++iProdItem)
if(!SymbolIsNullable(Symbol))
{
NullableSuffix = FALSE;
break;
}
if(NullableSuffix)
{
NProdItems = SymbolListCount(Rule->Symbols);
fprintf(stdout, "Conflicting rules in '%s'\n", SymbolStr(NonTerm));
DumpRule(stdout, Other);
DumpRule(stdout, Rule);
if(PrefixLen >= 0)
{
fprintf(stdout, "After common prefix of: ");
for(iProdItem=0; iProdItem < PrefixLen; ++iProdItem)
fprintf(stdout, " %s", SymbolStr(SymbolListGet(Rule->Symbols, iProdItem)));
fprintf(stdout, "\n");
}
fprintf(stdout, "this suffix is nullable: ");
for(iProdItem=PrefixLen; iProdItem < NProdItems; ++iProdItem)
fprintf(stdout, " %s", SymbolStr(Symbol=SymbolListGet(Rule->Symbols, iProdItem)));
fprintf(stdout, "\n");
if(PrefixLen == NProdItems - 1 && SymbolIsEqual(Symbol, NonTerm) && SymbolIsNullable(NonTerm))
{
fprintf(stdout, "Note: it appears that simply removing the shorter rule\n"
"would eliminate the ambiguity and be grammatically equivalent.\n"
);
}
exit(99);
}
}
/* CheckNullableRules() - see if two rules are both nullable.
*
* We already have a per-rule flag that tells us this, but
* we want to make an effort to make the error messages more
* intelligible.
*/
void CheckNullableRules(TSymbol* NonTerm, TRule* RuleA, TRule* RuleB)
{
/* if they are both nullable (then we will be terminating) */
if(RuleA->Nullable && RuleB->Nullable)
{
int CountA, CountB;
ErrorPrologue(ERROR_TWO_NULLABLE_RULES);
CountA = SymbolListCount(RuleA->Symbols);
CountB = SymbolListCount(RuleB->Symbols);
if(CountA == 0 && CountB == 0)
Error("'%s' contains two empty rules; can't choose between them.\n",
SymbolStr(NonTerm));
else if(CountA == 0 || CountB == 0)
{
Error("'%s' contains an empty rule and a nullable rule; can't choose between them.\n",
SymbolStr(NonTerm));
Error("The nullable rule is:\n %s : ", SymbolStr(NonTerm));
SymbolListDump(stderr, CountA?RuleA->Symbols:RuleB->Symbols, " ");
Error("\n");
}
else
Error("'%s' contains two nullable rules; can't choose between them.\n",
SymbolStr(NonTerm));
if(CountA)
DumpRule(stdout, RuleA);
if(CountB)
DumpRule(stdout, RuleB);
ErrorEpilog(-1);
}
}
/* CheckFirstFirstClash() - look for rules we can't choose between.
*
* If a nonterminal has two rules with intersecting FIRST sets,
* then we can't choose between them. This is complicated by
* any later grammar transformation that could cause a FIRST/FIRST
* clash to disappear. Obviously, left-factoring is one such
* transformation, since it's whole purpose is to remove a
* FIRST/FIRST clash. Left recursion removal is another case:
*
* lines
* :
* | lines line
* ;
*
* Here, because 'lines' is nullable, then it can both start with
* and be followed by a 'line'. But that problem will go away when
* the grammar is transformed to remove the left recursion.
*/
void CheckFirstFirstClash(void)
{
int iRule, jRule, NRules, iProdItem, MinCount, IsRecursiveA, IsRecursiveB;
TRule* RuleA;
TRule* RuleB;
TSymbol* SymA;
TSymbol* SymB;
SymIt NonTerm = SymItNew(Globals.NonTerms);
Dump("CheckFirstFirstClash()\n");
/* for each nonterminal */
while(SymbolIterate(&NonTerm))
{
if(NonTerm.Symbol->OperatorTrigger)
continue;
/* for each rule of this nonterminal */
NRules = RuleCount(NonTerm.Symbol);
for(iRule=0; iRule < NRules-1; ++iRule)
{
RuleA = NonTerm.Symbol->Rules[iRule];
IsRecursiveA = (SymbolListGet(RuleA->Symbols, 0) == NonTerm.Symbol);
/* compare rule to all others that follow */
for(jRule=iRule+1; jRule < NRules; ++jRule)
{
RuleB = NonTerm.Symbol->Rules[jRule];
CheckNullableRules(NonTerm.Symbol, RuleA, RuleB);
IsRecursiveB = (SymbolListGet(RuleB->Symbols, 0) == NonTerm.Symbol);
/* compare left recursive rules only to other left recursive rules */
if(IsRecursiveA != IsRecursiveB)
continue;
/* RewriteGrammar() will handle common left prefixes later */
if(CommonLeft(NonTerm.Symbol, RuleA->Symbols, RuleB->Symbols))
continue;
MinCount = SymbolListCount(RuleA->Symbols);
if(MinCount > SymbolListCount(RuleB->Symbols))
MinCount = SymbolListCount(RuleB->Symbols);
for(iProdItem=0; iProdItem < MinCount; ++iProdItem)
{
SYMBOLS Clash;
SYMBOLS FirstA=NULL, FirstB=NULL;
/* don't compare first symbol of left-recursive rules */
if(IsRecursiveA && iProdItem == 0)
continue;
SymA = SymbolListGet(RuleA->Symbols, iProdItem);
SymB = SymbolListGet(RuleB->Symbols, iProdItem);
if(SymA == SymB)
continue; /* skip over common left prefix */
/* form FIRST() sets for these rule suffixes */
FirstA = RuleFirst(NonTerm.Symbol, RuleA, iProdItem);
FirstB = RuleFirst(NonTerm.Symbol, RuleB, iProdItem);
Clash = SymbolListIntersect(FirstA, FirstB);
SymbolListDestroy(FirstA);
SymbolListDestroy(FirstB);
if(Clash)
{
ReportFirstFirstClash(NonTerm.Symbol, RuleA, RuleB, iProdItem, Clash);
// SymbolListDestroy(Clash);
}
break;
}
if(SymbolListCount(RuleA->Symbols) > MinCount)
CheckEpsilonClash(NonTerm.Symbol, RuleA, RuleB, iProdItem);
else if(SymbolListCount(RuleB->Symbols) > MinCount)
CheckEpsilonClash(NonTerm.Symbol, RuleB, RuleA, iProdItem);
}
}
}
Dump("CheckFirstFirstClash() done\n");
}
/* WhyFollow() - explain why terminal Term is in FOLLOW(NonTerm)
*
* For Term to be in FOLLOW(NonTerm), there must be some rule
* of a nonterminal X where NonTerm appears in the rhs of X and:
* 1) is followed by a string 'alpha', where FIRST(alpha) contains Term
* or
* 2) alpha is nullable (or nonexistent) and FOLLOW(X) contains Term
*
* We first locate a rhs occurrence of NonTerm that meets these criteria.
* If FIRST(alpha) contains Term, then we are done. Otherwise, we recurse
* to explain why FOLLOW(X) contains Term. As we unwind the recursion, we
* can print out a derivation (the derived string is stored in Derived)
* that explains in some detail why exactly Term is in FOLLOW(NonTerm).
*/
static
int WhyFollow(TSymbol* Target, TSymbol* Term, SYMBOLS Derived, TSymbol* SPtr)
{
int iProdItem, jProdItem, kProdItem, NProdItems, DLR;
TRule* Rule;
TRule** Rover;
SymIt NonTerm = SymItNew(Globals.NonTerms);
DumpVerbose("WhyFollow('%s', %s)\n", SymbolStr(Target), SymbolStr(Term));
/* for every nonterminal */
while(SymbolIterate(&NonTerm))
{
if(NonTerm.Symbol->OperatorTrigger) /* but skip LR(0) rules */
continue;
/* for every rule of this nonterminal */
Rover = NonTerm.Symbol->Rules;
if(Rover) for(; *Rover; ++Rover)
{
DLR = FALSE; /* assume rule is not direct left recursive */
Rule = *Rover;
/* for each rhs symbol of this rule */
NProdItems = SymbolListCount(Rule->Symbols);
for(iProdItem=0; iProdItem < NProdItems; ++iProdItem)
{
TSymbol* Symbol = SymbolListGet(Rule->Symbols, iProdItem);
TSymbol* Adjacent;
SYMBOLS AlphaFirst;
/* direct left recursion symbol is not what we want... */
if(iProdItem == 0 && Symbol == NonTerm.Symbol)
{
DLR = TRUE;
//printf("DLR=TRUE for rule %d\n", iRule);
// continue;
}
if(Symbol != Target)
continue;
/* At last, we found the target nonterminal in the rhs of a rule.
* So set Adjacent to symbol that follows our target non-terminal.
* (Still works fine even if no other symbols to right of this one.)
*/
/* skip any action items */
for(kProdItem=iProdItem+1; (Adjacent=SymbolListGet(Rule->Symbols, kProdItem)) != NULL; ++kProdItem)
if(!SymbolIsAction(Adjacent))
break;
else
{
printf("at pos %d, %s is action!\n", kProdItem, SymbolStr(Adjacent));
}
Adjacent = SymbolListGet(Rule->Symbols, kProdItem);
AlphaFirst = RuleFirst(NonTerm.Symbol, Rule, kProdItem);
#if 1
printf("Found symbol at pos %d in a rule for %s -> ", iProdItem, SymbolStr(NonTerm.Symbol));
SymbolListDump(stdout, Rule->Symbols, " ");
printf("\nAlphaFirst(%d)=", kProdItem);
SymbolListDump(stdout, AlphaFirst, " ");
printf("\nFOLLOW(%s)=", SymbolStr(NonTerm.Symbol));
SymbolListDump(stdout, NonTerm.Symbol->Follow, " ");
printf("\n");
#endif
/* if this rule could explain why Term is in FOLLOW(Target) */
if( SymbolListContains(AlphaFirst, Term)
|| ( RuleNullable(Rule, kProdItem)
&& SymbolListContains(NonTerm.Symbol->Follow, Term)
)
)
{
printf("\n%d Found rule to explain it (k=%d): %s ", SymbolListContains(AlphaFirst, Term), kProdItem, SymbolStr(NonTerm.Symbol));
DumpRule(stdout, Rule);
/* NonTerm -> ... Target alpha
* if Term is not in FIRST(alpha), then must explain
* why it is in FOLLOW(NonTerm) by recursing
*/
if(!SymbolListContains(AlphaFirst, Term))
{
jProdItem = WhyFollow(NonTerm.Symbol, Term, Derived, SPtr);
/* here is where we are unwinding after recursing */
Error("%s -> ", SymbolStr(NonTerm.Symbol));
SymbolListDump(stderr, Rule->Symbols, "{ ");
if(kProdItem < NProdItems)
{
Error(" (where ");
while((Symbol=SymbolListGet(Rule->Symbols, kProdItem)) != NULL)
Error("%s ", SymbolStr(Symbol));
Error("is nullable)");
}
Error("\n");
SymbolListReplace(Derived, jProdItem, Rule->Symbols);
Error(" [ ");
SymbolListDump(stderr, Derived, "{ ");
Error(" ]\n");
return iProdItem + jProdItem;
}
/* NonTerm -> ... Target Adjacent ...
* At this point, Adjacent is either Term or else
* FIRST(Adjacent) contains Term.
*/
else if(Adjacent && Adjacent != Term)
{
assert(SymbolListContains(Adjacent->First, Term));
Error(", where '%s' can start with a '%s':\n", SymbolStr(Adjacent), SymbolStr(Term));
}
else
Error(":\n"); /* finish off "Consider this derivation" */
/* here is where the topmost derivation is emitted*/
Error("%s -> ", SymbolStr(NonTerm.Symbol));
SymbolListDump(stderr, Rule->Symbols, "{ ");
Error("\n");
SymbolListCopy(Derived, Rule->Symbols);
Error(" [ ");
SymbolListDump(stderr, Rule->Symbols, "{ ");
Error(" ]\n");
if(Symbol == NULL)
{
Error("%s -> ", SymbolStr(NonTerm.Symbol));
SymbolListDump(stderr, Rule->Symbols, "{ ");
Error("\n");
SymbolListReplace(Derived, 0, Rule->Symbols);
Error(" [ ");
SymbolListDump(stderr, Derived, "{ ");
Error(" ]\n");
}
return iProdItem;
}
if(AlphaFirst)
SymbolListDestroy(AlphaFirst);
}
}
}
fflush(stdout);
fflush(stderr);
assert(FALSE); /* should not reach here */
return FALSE;
}
/* CheckSuffix() - try to distinguish suffixes of a common left prefix.
*
* We found two rules with a common left prefix. To make sure we will
* later be able to factor that common prefix out (and end up with an
* LL(1) grammar), we need to know that the suffixes can be distinguished
* from each other.
*/
static
int SuffixFirst(SYMBOLS* First, SYMBOLS List, int Pos)
{
TSymbol* Symbol;
int Nullable = TRUE;
while((Symbol=SymbolListGet(List, Pos)) != NULL)
{
*First = SymbolListAddFirst(*First, Symbol);
if(Symbol->Nullable)
++Pos;
else
{
Nullable = FALSE;
break;
}
}
return Nullable;
}
static
void CheckSuffix(TSymbol* NonTerm, SYMBOLS AList, int iA, SYMBOLS BList, int iB)
{
int ANullable, BNullable;
SYMBOLS FirstA = NULL;
SYMBOLS FirstB = NULL;
SYMBOLS Clash = NULL;
ANullable = SuffixFirst(&FirstA, AList, iA);
BNullable = SuffixFirst(&FirstB, BList, iB);
Clash = SymbolListIntersect(FirstA, FirstB);
assert(SymbolListCount(Clash) == 0);
if(ANullable && BNullable)
{
SYMBOLS Temp;
ErrorPrologue(ERROR_SUFFIXES_NULLABLE);
Error("Can't choose between two rules:\n %s : ", SymbolStr(NonTerm));
SymbolListDump(stderr, AList, "{ ");
Error("\n %s : ", SymbolStr(NonTerm));
SymbolListDump(stderr, BList, "{ ");
Error("\nAfter the common left prefix of:\n ");
Temp = SymbolListTruncate(SymbolListCopy(NULL, AList), iA);
SymbolListDump(stderr, Temp, "{ ");
Error("\nboth suffixes are nullable.\n");
ErrorEpilog(-1);
}
assert(!(ANullable && BNullable));
}
/* CommonLeft() - check two rules for common left prefixes.
*
* Two errors are checked for:
* A) two rules that are identical
* B) a common left prefix that contains embedded actions
*
* If no errors were encountered, the length of the common prefix
* (if any) of the two rules is returned.
*/
int CommonLeft(TSymbol* NonTerm, SYMBOLS AList, SYMBOLS BList)
{
int iA, nA, iB, nB;
TSymbol* A;
TSymbol* B;
SYMBOLS Common = NULL;
int MatchCount;
int ActionCount, FoundActions, LastSymbolMatched;
DumpVerbose(". CommonLeft('%s') comparing rules:\n. -> ", SymbolStr(NonTerm));
SymbolListDump(stdout, AList, " ");
DumpVerbose("\n. -> ");
SymbolListDump(stdout, BList, " ");
DumpVerbose("\n");
nA = SymbolListCount(AList);
nB = SymbolListCount(BList);
// assert(nA > 0 && nB > 0);
ActionCount = 0;
FoundActions = FALSE;
LastSymbolMatched = FALSE;
A = B = NULL;
for(iA=iB=0; iA < nA || iB < nB; ++iA,++iB)
{
/* advance to next "real" symbol in AList (if any) */
for(A = NULL; iA < nA; ++iA)
{
A = SymbolListGet(AList, iA);
if(SymbolIsAction(A))
{
A = NULL;
++ActionCount;
}
else
break;
}
/* advance to next "real" symbol in BList (if any) */
for(B = NULL; iB < nB; ++iB)
{
B = SymbolListGet(BList, iB);
if(SymbolIsAction(B))
{
B = NULL;
++ActionCount;
}
else
break;
}
/* if there was another symbol in both productions */
if(A != NULL || B != NULL)
{
/* If both productions share another prefix symbol */
if(A == B)
{
LastSymbolMatched = TRUE;
if(ActionCount)
FoundActions = TRUE;
Common = SymbolListAdd(Common, A);
continue;
}
else
{
LastSymbolMatched = FALSE;
break;
}
}
/* else, we must have exhausted both lists */
assert(iA >= nA && iB >= nB);
}
MatchCount = SymbolListCount(Common);
if(LastSymbolMatched == TRUE)
{
ErrorPrologue(ERROR_RULES_ARE_IDENTICAL);
Error("Nonterminal '%s' has two or more rules with identical symbols:\n", SymbolStr(NonTerm));
SymbolListDump(stderr, Common, " ");
Error("\n");
ErrorEpilog(-1);
}
/* */
else if(MatchCount > 0)
{
Dump(" # of common left symbols=%d: ", SymbolListCount(Common));
SymbolListDump(stdout, Common, " ");
printf("\n");
if(FoundActions)
{
ErrorPrologue(ERROR_COMMON_PREFIX_CONTAINS_ACTION);
Error("Nonterminal '%s': %s\n",
SymbolStr(NonTerm),
"two rules share a common prefix containing embedded actions\n");
Error(" -> ");
SymbolListDump(stderr, AList, " ");
Error("\n");
Error(" -> ");
SymbolListDump(stderr, BList, " ");
Error("\n");
Exit(-1, ERROR_COMMON_PREFIX_CONTAINS_ACTION);
}
CheckSuffix(NonTerm, AList, iA, BList, iB);
}
if(Common)
SymbolListDestroy(Common);
//fprintf(stderr, " LastSymbolMatched=%d, MatchCount=%d\n", LastSymbolMatched, MatchCount);
return MatchCount;
}
/* CheckFirstFollowClash() - give reasonable message when FIRST(N) intersects FOLLOW(N)
*
* Suppose N is a nullable nonterminal whose FIRST set and FOLLOW set
* both contain one or more of the same terminals (I'll use 'x' in this
* example). Then the grammar is not LL(1), since when N is on top of
* the stack and the next input terminal is 'x', we can't decide whether
* to let N eat this 'x' or choose its nullable alternative so that
* whatever comes after the N can eat the 'x' (which we know is possible,
* else 'x' would not be in FOLLOW(N)).
*
* However, it is often quite tedious for the user to figure out why
* 'x' is in FOLLOW(N), so this function takes pains to explain why.
*
* Basically, if 'x' is in FOLLOW(N), then we must be able to find
* some rule like this:
*
* M : ... N alpha
*
* where either FIRST(alpha) contains 'x', or alpha is nullable
* and FOLLOW(M) contains 'x'. If FIRST(alpha) contains 'x', then
* we report which symbol in alpha caused that to be true. Otherwise,
* we recurse to indicate why FOLLOW(M) contains 'x'.
*
*/
void CheckFirstFollowClash(void)
{
int iProdItem, NProdItems;
TRule* Rule;
TRule** Rover;
TSymbol* X;
TSymbol* Y;
SymIt NonTerm = SymItNew(Globals.NonTerms);
Dump("CheckFirstFollowClash()\n");
/* for every nonterminal */
while(SymbolIterate(&NonTerm))
{
/* Well, not "every" nonterminal */
if(SymbolIsAction(NonTerm.Symbol))
continue;
/* for each rule of this non-terminal */
Rover = NonTerm.Symbol->Rules;
if(Rover) for(; *Rover; ++Rover)
{
/* for each production item of this rule */
Rule = *Rover;
NProdItems = SymbolListCount(Rule->Symbols);
for(iProdItem=0; iProdItem < NProdItems; ++iProdItem)
{
SYMBOLS Clash, SuffixFirst;
X = SymbolListGet(Rule->Symbols, iProdItem);
if(!X->Nullable || !X->FirstFollowClash)
continue;
/* ignore first symbol in simple left recursive rule ???*/
if(iProdItem == 0 && X == NonTerm.Symbol)
continue;
Clash = SymbolListIntersect(X->First, X->Follow);
if(Clash)
{
TSymbol* Clash1 = SymbolListGet(Clash, 0);
TSymbol* First = NULL;
ErrorPrologue(ERROR_A_NULLABLE_B_CLASH);
Error("Can't decide whether '%s' should consume a '%s' or nothing\n"
"(it's nullable), "
"since it can also be followed by a '%s'.\nConsider this derivation",
SymbolStr(X), SymbolStr(Clash1), SymbolStr(Clash1));
ReportFirstFirstExample(X, Clash1);
//Error("WhyFollow(%s, %s)!!!!!!\n", SymbolStr(X), SymbolStr(SymbolListGet(Clash, 0)));
WhyFollow(X, Clash1, SymbolListCreate(), First);
SymbolListDestroy(Clash);
if(First)
{
ReportFirstFirstExample(First, Clash1);
}
ErrorEpilog(0);
}
else
continue;
Y = SymbolListGet(Rule->Symbols, iProdItem+1);
SuffixFirst = RuleFirst(NonTerm.Symbol, Rule, iProdItem+1);
Clash = SymbolListIntersect(X->First, SuffixFirst);
SymbolListDestroy(SuffixFirst);
if(Clash)
{
ErrorPrologue(ERROR_A_NULLABLE_B_CLASH);
Error("Clash on %s %s in: %s -> ", SymbolStr(X), SymbolStr(Y), SymbolStr(NonTerm.Symbol));
SymbolListDump(stderr, Rule->Symbols, " ");
Error("\n'%s' is nullable, but both '%s' and '%s' can start with: ",
SymbolStr(X), SymbolStr(X), SymbolStr(Y));
SymbolListDump(stderr, Clash, " ");
Error("\n");
ErrorEpilog(-1);
}
}
}
}
Dump("CheckFirstFollowClash() returns\n");
}
/* CheckLeftRecursion() - identify/report instances of left recursion.
*
* The primary motivation for this step is to give a better error
* message than what would emerge when we try to construct the LL(1)
* parsing table.
*/
typedef struct TState
{
int iRule;
int iRhs;
TSymbol* Suspect;
TRule* Rule;
} TState;
static
int CheckLeftPopStack(TState *State, int StackTop, TState* Stack)
{
//printf("pop '%.*s'\n", State->Suspect->Name.TextLen, State->Suspect->Name.Text);
if(--StackTop >= 0)
{
TSymbol* Suspect = State->Suspect;
*State = Stack[StackTop];
if(Suspect->Nullable)
++State->iRhs;
else
{
++State->iRule;
State->iRhs = -1;
}
}
return StackTop;
}
static
void ReportLeftRecursion(TState* Stack, int StackTop)
{
int i;
fprintf(stderr, "Left recursion (x* indicates x is nullable):\n");
for(i = 0; i < StackTop; ++i)
{
int iProdItem;
TRule* Rule = Stack[i].Rule;
fprintf(stderr, " %.*s: ", Stack[i].Suspect->Name.TextLen, Stack[i].Suspect->Name.Text);
for(iProdItem = 0; iProdItem < SymbolListCount(Rule->Symbols); ++iProdItem)
{
TSymbol* Symbol = SymbolListGet(Rule->Symbols, iProdItem);
fprintf(stderr, "%.*s", Symbol->Name.TextLen, Symbol->Name.Text);
if(Symbol->Nullable)
fprintf(stderr, "* ");
else
fprintf(stderr, " ");
}
fprintf(stderr, "\n");
}
}
static
int CheckLeft(TSymbol* NonTerm, TState* Stack, SYMBOLS Tried)
{
TState State = {0};
int ErrorCount = 0;
int StackTop = 0;
/* State is logically Stack[StackTop] */
State.iRule = -1;
State.Suspect = NonTerm;
while(StackTop >= 0)
{
if(StackTop < 0) /* if no more symbols on stack */
return ErrorCount;
/* if starting new non-terminal */
else if(State.iRule < 0)
{
/* see if new entry proves left-recursion */
if(StackTop > 0 && State.Suspect == NonTerm)
{
++ErrorCount;
ReportLeftRecursion(Stack, StackTop);
StackTop = CheckLeftPopStack(&State, StackTop, Stack);
/*??? then what ???*/
}
/* else if we have already gone down this path before */
else if(SymbolListContains(Tried, State.Suspect) || State.Suspect->OperatorTrigger)
StackTop = CheckLeftPopStack(&State, StackTop, Stack);
/* else, get ready to walk through rules in this suspect */
else
{
SymbolListAdd(Tried, State.Suspect);
State.iRule = 0;
State.iRhs = -1;
}
}
else if(State.iRule >= RuleCount(State.Suspect))
StackTop = CheckLeftPopStack(&State, StackTop, Stack);
/* if starting a new rule */
else if(State.iRhs == -1)
{
/* if no more rules in this non-terminal */
if(State.iRule >= RuleCount(State.Suspect))
StackTop = CheckLeftPopStack(&State, StackTop, Stack);
else
{
State.Rule = State.Suspect->Rules[State.iRule];
State.iRhs = 0;
}
}
/* if no more symbols in this RHS */
else if(State.iRhs >= SymbolListCount(State.Rule->Symbols))
{
State.iRhs = -1;
++State.iRule;
}
/* else, we are examining a RHS symbol in a rule from the current non-terminal */
else
{
TSymbol* Symbol = SymbolListGet(State.Rule->Symbols, State.iRhs);
if(SymbolGetBit(Symbol, SYM_TERMINAL))
{
State.iRhs = -1;
++State.iRule;
}
/* else, get ready to push new symbol on stack */
else
{
//printf("push '%.*s'\n", Symbol->Name.TextLen, Symbol->Name.Text);
Stack[StackTop++] = State;
State.Suspect = Symbol;
State.iRule = -1;
}
}
}
return ErrorCount;
}
static
void ReportLeftRecursionClash(TSymbol* Lhs, TRule* Rule, SYMBOLS Clashes)
{
fprintf(stdout, "%s can both start with and be followed by: ", SymbolStr(Lhs));
SymbolListDump(stdout, Clashes, ", ");
fprintf(stdout, "\n");
fprintf(stdout, "which is not allowed for this left-recursive rule:\n%s -> ", SymbolStr(Lhs));
SymbolListDump(stdout, Rule->Symbols, " ");
fprintf(stdout, "\n");
exit(999);
}
/* SimpleLeftRecursion() - return true if it's left recursion we handle.
*
* We handle "immediate self recursion", of the form:
*
* A -> A <stuff>
*
* so we don't want to warn about it. However, note that <stuff> must
* not be empty or nullable -- that case will already have been detected
* by CheckCircularity() before we are called.
*
* Note the impending transformation to:
*
* A -> <stuff> `A
* `A -> <epsilon>
* | <stuff> `A
*
* Also, FIRST(<stuff>) must not intersect FOLLOW(A). We will exert
* effort to produce an intelligent error message for such cases.
*/
static
int SimpleLeftRecursion(TSymbol* Lhs)
{
int Result;
TRule** Rover;
Result = FALSE; /* assume it's not simple left recursion */
/* for each production of this non-terminal */
Rover = Lhs->Rules;
if(Rover) for(; *Rover; ++Rover)
{
int NSymbols, iSymbol;
TRule* Rule = *Rover;
assert(Rule != NULL);
NSymbols = SymbolListCount(Rule->Symbols);
for(iSymbol=0; iSymbol < NSymbols; ++iSymbol)
{
TSymbol* Rhs = SymbolListGet(Rule->Symbols, iSymbol);
assert(Rhs != NULL);
if(SymbolIsAction(Rhs))
continue;
if(Rhs == Lhs) /* if first "real" symbol same as left-hand side */
{
SYMBOLS Clashes;
TSymbol* Symbol;
Symbol = SymbolListGet(Rule->Symbols, 1);
Clashes = SymbolListIntersect(Symbol->First, Lhs->Follow);
if(SymbolListCount(Clashes))
ReportLeftRecursionClash(Lhs, Rule, Clashes);
SymbolListDestroy(Clashes);
}
}
}
return Result;
}
void CheckLeftRecursion(void)
{
int ErrorCount;
int iNonTerm, NNonTerms;
TState* Stack;
if(Globals.Dump)
printf("CheckLeftRecursion!\n");
NNonTerms = SymbolListCount(Globals.NonTerms);
Stack = (TState*)malloc(sizeof(TState)*(NNonTerms+1));
assert(Stack != NULL);
ErrorCount = 0;
/* Check each non-terminal for left-recursion */
for(iNonTerm = 0; iNonTerm < NNonTerms; ++iNonTerm)
{
TSymbol* NonTerm;
NonTerm = SymbolListGet(Globals.NonTerms, iNonTerm);
if(!NonTerm->LeftRecursive)
{
SYMBOLS Tried = SymbolListCreate();
ErrorCount += CheckLeft(NonTerm, Stack, Tried);
SymbolListDestroy(Tried);
}
}
if(ErrorCount)
ErrorExit(ERROR_LEFT_RECURSION, "%d instance%s of left recursion.",
ErrorCount, ErrorCount > 1 ? "s" : "");
free(Stack);
}
|
100siddhartha-blacc
|
check.c
|
C
|
mit
| 75,088
|
#include "operator.h"
#include "globals.h"
#include "bitset.h"
/* operator.c - operator precedence code.
*
* Apart from parsing input, most of the work related to creating the necessary
* tables for operator precedence parsing is here.
*/
#define LEFT_HANDLE (-1)
#define RIGHT_HANDLE (1)
#define MIDDLE_HANDLE (0)
#define ERROR_HANDLE (-99)
/* TOpSym
*
* TOperator describes an operator, but an operator can comprise more
* than one symbol. The operator precedence parser will be dealing with
* individual symbols, as well most of the calculation we need to do
* for constructing precedence functions.
*/
typedef struct TOpSym
{
TOperator* Operator; /* ptr to operator that contains this symbol */
int ListIndex; /* index of this symbol in the operator string */
int OpSymVal; /* operator symbols are numbered sequentially */
} TOpSym;
static const char* OpSymStr(TOpSym* OpSym);
int* FGTable;
static TOpSym** OpSyms;
static int NOpSyms;
static TOperator** Operators;
static int NOperators;
static int NGroups;
static int MaxGroups;
static int* Groups;
static int NFGSyms;
static int* FGSyms;
static int NEdges;
static int* Edges;
void OperatorFree(void)
{
int iOp;
for(iOp=0; iOp < NOperators; ++iOp)
{
free((void*)Operators[iOp]->Pattern);
SymbolListDestroy(Operators[iOp]->List);
free(Operators[iOp]);
}
if(Operators)
free(Operators);
if(OpSyms)
{
for(iOp=0; iOp < NOpSyms; ++iOp)
free(OpSyms[iOp]);
free(OpSyms);
}
// if(FTable)
// free(FTable);
// if(GTable)
// free(GTable);
// if(Edges)
// free(Edges);
if(Groups)
free(Groups);
if(FGSyms)
free(FGSyms);
}
int OpSymMatch(TOpSym* OpSym, const char* Pattern)
{
int Result;
char Target[MAX_OPERATOR_PATTERN+1];
strcpy(Target, OpSym->Operator->Pattern);
Target[OpSym->ListIndex] = '@';
Result = PatternCmp(Pattern, Target) >= 0;
//printf("OpSymMatch('%s', '%s') = %d\n", OpSymStr(OpSym), Pattern, Result);
return Result;
}
/* OpSymAdd() - try to add operator symbol to global list
*
* The complication is homonyms.
*/
TOpSym* OpSymAdd(TOperator* Operator, int ListIndex)
{
TOpSym* OpSym = NEW(TOpSym);
assert(OpSym != NULL);
OpSym->Operator = Operator;
OpSym->ListIndex = ListIndex;
OpSym->OpSymVal = NOpSyms;
++NOpSyms;
OpSyms = (TOpSym**)realloc(OpSyms, sizeof(TOpSym*)*NOpSyms);
assert(OpSyms != NULL);
OpSyms[NOpSyms-1] = OpSym;
return OpSym;
}
/* OperatorAdd_() - actual workhorse to add a new operator.
*
*/
static
void OperatorAdd_(TToken Decl, int Precedence, int Associativity, SYMBOLS List, const char* Pattern)
{
int iSymbol;
TSymbol* Symbol;
TOperator* Result = NEW(TOperator);
assert(Result != NULL);
Result->Precedence = Precedence;
Result->Associativity = Associativity;
Result->List = List;
Result->Decl = Decl;
Result->Pattern = StrClone(Pattern);
++NOperators;
Result->IntRep = NOperators;
Operators = (TOperator**)realloc(Operators, sizeof(TOperator*)*NOperators);
assert(Operators != NULL);
Operators[NOperators-1] = Result;
for(iSymbol = 0; iSymbol < SymbolListCount(List); ++iSymbol)
{
Symbol = SymbolListGet(List, iSymbol);
if(Symbol)
{
OpSymAdd(Result, iSymbol);
++Result->SymCount;
}
}
}
void OperatorAdd(TToken Decl, int Precedence, int Associativity, SYMBOLS List, const char* Pattern)
{
static int Initialized;
/* We implicitly add the EOF token as an operator before any
* other operators. It's an appropriate place to do so, since
* $ is more or less the highest precedence operator (and higher
* precedence is associated with operators defined earlier in
* the BLACC input).
*/
if(!Initialized)
{
TToken Operand = TokenFake(TK_IDENT, "<id>");
TSymbol* EofSym;
TSymbol* OperandSym;
SYMBOLS EofList = NULL;
SYMBOLS OperandList = NULL;
EofSym = SymbolFind(EOFToken);
assert(EofSym != NULL);
/* first, add the $ operator (our logical EOF) */
EofList = SymbolListAdd(EofList, SymbolFind(EOFToken));
OperatorAdd_(EOFToken, 99999, TK_NONASSOC, EofList, ".");
/* second, add the operand "operator" */
OperandSym = SymbolAdd(Operand, SYM_TERMINAL);
OperandList = SymbolListAdd(OperandList, OperandSym);
OperatorAdd_(Operand, 0, TK_NONASSOC, OperandList, ".");
Initialized = TRUE;
}
OperatorAdd_(Decl, Precedence, Associativity, List, Pattern);
}
TOperator* OperatorGet(int Which)
{
TOperator* Result = NULL;
assert(Which >= 0);
if(Which < NOperators)
Result = Operators[Which];
return Result;
}
/* OperatorCount() - global function to return total # of operators.
*/
int OperatorCount(void)
{
return NOperators;
}
/* OperatorFindOpSym() - Locate an operator that contains a given symbol.
*
* Sometimes an operator is simply a symbol, but sometimes it contains
* multiple symbols. For example, searching for the operator symbol ')'
* will match operators like "(X)", "X(X)", and "(X)X".
*/
TOperator* OperatorFindOpSym(TOperator* Start, TSymbol* OpSym)
{
int iOperator, iSymbol, NSymbols;
TOperator* Operator;
iOperator = 0;
if(Start)
for(; iOperator < NOperators; ++iOperator)
if(Operators[iOperator] == Start)
break;
for(++iOperator; iOperator < NOperators; ++iOperator)
{
Operator = Operators[iOperator];
NSymbols = SymbolListCount(Operator->List);
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
if(SymbolListGet(Operator->List, iSymbol) == OpSym)
return Operator;
}
return NULL;
}
/*********************************************************************
* code to calculate operator precedence tables.
*********************************************************************/
#define GFLAG 0x8000
typedef struct TGroup
{
int iOpSym;
int iEdge;
} TGroup;
/* OpSymStr() - create human-readable string to identify operator symbol
*
* We need to print debug information about a particular symbol from
* a particular operator.
*/
#define MAX_SYM_STR (64)
static const char* OpSymStr(TOpSym* OpSym)
{
static char Buffer[256];
static char*Rover = Buffer;
char* Result;
SYMBOLS List = OpSym->Operator->List;
int iList;
TSymbol* Sym;
assert(OpSym != NULL);
if(Rover - Buffer > sizeof(Buffer)-MAX_SYM_STR)
Rover = Buffer;
Rover[0] = '\0';
if(OpSym->Operator->SymCount > 1)
{
for(iList=0; iList < SymbolListCount(List); ++iList)
{
Sym = SymbolListGet(List, iList);
if(Sym == NULL)
strcat(Rover, "X");
else
{
TToken Token = LiteralFromSymbol(Sym);
if(OpSym->ListIndex == iList)
strcat(Rover, "@");
if(Token.Text == NULL)
Token = Sym->Name;
Token = Unquote(Token);
strncat(Rover, Token.Text, Token.TextLen);
}
}
}
else
sprintf(Rover, "%.*s", OpSym->Operator->Decl.TextLen, OpSym->Operator->Decl.Text);
Result = Rover;
Rover += strlen(Rover)+1;
return Result;
}
/* CreateGroups() - partition our pseudo-symbols into groups.
*
* For each symbol (operator, operand, or $), we will create two
* pseudo-symbols: call them the F and G versions of the original.
*
* We then partition them into groups, such that if a = b (= being
* used in the precedence relation sense here), then Fa and Gb must
* be in the same group.
*
* That's the general algorithm, but the specifics are much simpler
* for BLACC. In effect, most operators do not have the = precedence
* relation to each other, so each pseudo-operator simply goes in a
* "group" by itself.
*
* The exceptions are multi-symbol operators like "()", "[]", and
* "?:". For example, given the operator precedence specification of
* "X?X:X", then ? and : will have a precedence relation of =.
*
* The fact that we do not allow the same symbol to be used in multiple
* operators (except under a couple of well-defined situations) keeps
* more complex cases from arising for the partitioning algorithm.
*
*/
/* FromSameOperator() - do these tokens both appear in the same operator?
*/
static
int FromSameOperator(int OpTokA, int OpTokB)
{
int Result = TRUE;
if(OpTokA != OpTokB)
{
if(OpTokA < 0 || OpTokA >= NOpSyms || OpTokB < 0 || OpTokB >= NOpSyms)
Result = FALSE;
else
Result = (OpSyms[OpTokA]->Operator == OpSyms[OpTokB]->Operator);
}
return Result;
}
/*
* Groups:
* Groups is an integer array. Even elements in Groups
* contain an offset into FGSyms, while odd elements contain
* an offset into Edges (or -1). Conceptually, even elements
* in Groups "point" to a sequence of one or more F/G symbols
* in FGSyms that represent the one or more symbols in that group.
*/
static
void CreateGroups(void)
{
int iFGSym, iOpSym;
iFGSym = 0;
/* for each operator symbol (i.e., the "?:" operator contains 2 operator symbols)
*/
for(iOpSym = 0; iOpSym < NOpSyms; ++iOpSym)
{
/* start new group with F(current symbol) */
Groups[NGroups*2] = iFGSym;
Groups[NGroups*2+1] = -1; /* no edges yet */
++NGroups;
assert(NGroups <= MaxGroups);
FGSyms[iFGSym++] = iOpSym;
/* if non-last symbol in a multi-symbol operator*/
if(FromSameOperator(iOpSym, iOpSym+1))
{
/* add G(next symbol) to current group */
FGSyms[iFGSym++] = (iOpSym+1) | GFLAG;
}
/* if our G was already put in a previous group */
if(FromSameOperator(iOpSym-1, iOpSym))
;
/* else, our G gets its own group */
else
{
Groups[NGroups*2] = iFGSym;
Groups[NGroups*2+1] = -1; /* no edges yet */
++NGroups;
assert(NGroups <= MaxGroups);
FGSyms[iFGSym++] = iOpSym | GFLAG;
}
}
NFGSyms = iFGSym;
if(Globals.Dump)
{
int iGroup;
printf("Groups:\n");
for(iGroup=0; iGroup < NGroups; ++iGroup)
{
printf(" [%3d] ", iGroup);
iFGSym = Groups[iGroup*2];
do
{
iOpSym = FGSyms[iFGSym];
printf("%c(%s) ", (iOpSym&GFLAG)?'G':'F', OpSymStr(OpSyms[iOpSym&~GFLAG]));
++iFGSym;
} while(iFGSym < Groups[(iGroup+1)*2]);
printf("\n");
}
}
}
static
int LeftMostSym(int iOpSym, TOpSym* OpSym)
{
return OpSym->Operator->SymCount > 1
&& !FromSameOperator(iOpSym, iOpSym-1);
}
static
int RightMostSym(int iOpSym, TOpSym* OpSym)
{
return OpSym->Operator->SymCount > 1
&& !FromSameOperator(iOpSym, iOpSym+1);
}
/* LeftInterior() - is this left interior of multi-token operator?
*
* For example, is this the '[' in 'X[X]'? In this case, the '['
* effectively has to compete for precedence with any operator to
* the left.
*/
static int LeftInterior(int iOpSym, TOpSym* OpSym)
{
return OpSym->Operator->SymCount > 1 /* multisym operator */
&& OpSym->ListIndex != 0 /* */
&& FromSameOperator(iOpSym, iOpSym+1);
}
/* RightInterior() - is this right interior of multi-token operator?
*
* For example, is this the ')' in 'X(X)'? In this case, the ')'
* effectively has to compete for precedence with any operator to
* the right.
*/
static int RightInterior(int iOpSym, TOpSym* OpSym)
{
return OpSym->Operator->SymCount > 1 && FromSameOperator(iOpSym-1, iOpSym);
}
static int IsEnclosure(TOperator* Operator)
{
const char* Pattern = Operator->Pattern;
size_t Len = strlen(Pattern);
return Len >= 3
&& Pattern[0] == '.'
&& Pattern[strlen(Pattern)-1] == '.'
;
}
/* RightEnd() - is this the right-most symbol of a post-unary operator?
*/
static int RightEnd(TOpSym* OpSym)
{
int Result;
const char* Pattern = OpSym->Operator->Pattern;
size_t Len = strlen(Pattern);
Result= Len >= 2
&& Pattern[strlen(Pattern)-1] == '.'
&& OpSym->ListIndex == SymbolListCount(OpSym->Operator->List) - 1
;
#if 0
printf("RightEnd(ListIndex=%d of %d, %s, %s) = %d\n",
OpSym->ListIndex, SymbolListCount(OpSym->Operator->List), OpSymStr(OpSym), Pattern, Result);
#endif
return Result;
}
/* LeftEnclosure() - is this a left enclosure of a multi-token operator?
*
* For example, is this the '(' in '(X)'? In this case, the '('
* always identifies the start of a handle.
*/
static int LeftEnclosure(int iOpSym, TOpSym* OpSym)
{
return OpSym->Operator->SymCount > 1
&& !FromSameOperator(iOpSym-1, iOpSym)
&& OpSym->ListIndex == 0
;
}
/* RightEnclosure() - is this a right enclosure of a multi-token operator?
*
* For example, is this the ')' in '(X)'? In this case, the ')'
* always identifies the end of a handle.
*/
static int RightEnclosure(int iOpSym, TOpSym* OpSym)
{
//fprintf(stdout, "RightEnclosure(%d)\n", iOpSym);
return OpSym->Operator->SymCount > 1
&& !FromSameOperator(iOpSym, iOpSym+1)
&& OpSym->ListIndex == SymbolListCount(OpSym->Operator->List)-1
;
}
static int FirstSymInOp(int iOpSym)
{ return !FromSameOperator(iOpSym-1, iOpSym); }
static int LastSymInOp(int iOpSym)
{ return !FromSameOperator(iOpSym, iOpSym+1); }
static
int PatCmp(const char* Pattern, TOpSym* OpSym)
{
size_t Len;
const char* Decl;
Len = OpSym->Operator->Decl.TextLen;
Decl = OpSym->Operator->Decl.Text;
while(Len > 0 && *Pattern)
{
if(*Pattern == '.' && *Decl == 'X')
break;
else if(*Pattern == 'X' && *Decl != 'X')
break;
--Len;
++Pattern;
++Decl;
}
return Len <= 0 && *Pattern == '\0';
}
static int OpRelationError(int iOpSymA, TOpSym* OpSymA, int iOpSymB, TOpSym* OpSymB)
{
int Result = FALSE;
/* f$ <--> g$, no precedence relation (empty input not allowed) */
if(iOpSymA == 0 && iOpSymB == 0)
Result = TRUE;
/* f$ can't pop up in middle of multi-symbol operator */
else if(FromSameOperator(iOpSymB-1, iOpSymB) && iOpSymA == 0)
Result = TRUE;
/* g$ can't pop up in middle of multi-symbol operator */
else if(FromSameOperator(iOpSymA, iOpSymA+1) && iOpSymB == 0)
Result = TRUE;
/* LR(0) won't ask us, but <id> <id> is an error*/
else if(iOpSymA == 1 && iOpSymB == 1)
Result = TRUE;
/* left side is end of a grouping operator, right side must
* not be id or prefix operator
*/
else if (OpSymMatch(OpSymA, "X@$") /* lhs is end of grouping op*/
&& (iOpSymB == 1 /* rhs is <id> */
|| OpSymMatch(OpSymB, "^@") /* rhs is prefix operator */
)
)
Result = TRUE;
/* right side is start of a grouping operator, left side must
* not be id or postfix operator
*/
else if (OpSymMatch(OpSymB, "^@X") /* rhs is end of grouping op */
&& (iOpSymA == 1 /* lhs is <id> */
|| OpSymMatch(OpSymB, "@$") /* lhs is postfix operator */
)
)
Result = TRUE;
#if 0
/* postfix on left requires right bracket or EOF or binop on right */
else if (OpSymMatch(OpSymA, "X*@$")
&& (iOpSymB != 0 )
)
Result = TRUE;
/* LR(0) never inquires "precedence" of operand */
else if(iOpSymA == 1 || iOpSymB == 1 || IsEnclosure(OpSymA->Operator) || IsEnclosure(OpSymB->Operator))
Result = TRUE;
/* id id, no precedence relation */
else if(iOpSymA == 1 && iOpSymB == 1)
Result = TRUE;
/*??? probably not general enough*/
/* id .X., no precedence relation */
else if(iOpSymA == 1 && PatCmp(".X.", OpSymB) && !FromSameOperator(iOpSymB-1, iOpSymB))
Result = TRUE;
/* .X. id, no precedence relation */
else if(iOpSymB == 1 && PatCmp(".X.", OpSymA) && !FromSameOperator(iOpSymA, iOpSymA+1))
Result = TRUE;
#endif
/* can't interleave two different distfix operators */
else if(!FromSameOperator(iOpSymA, iOpSymB)
&& OpSymA->Operator->SymCount > 1
&& OpSymB->Operator->SymCount > 1
&& !
(RightMostSym(iOpSymA, OpSymA) || LeftMostSym(iOpSymB, OpSymB))
)
Result = TRUE;
/* 2 symbols from same multi-symbol operator */
else if(FromSameOperator(iOpSymA, iOpSymB) && OpSymA->Operator->SymCount > 1)
{
/* if in defined sequence */
if(iOpSymA == iOpSymB-1)
; /* then that's OK */
/* if right-hand could represent start of nested operator */
else if(FirstSymInOp(iOpSymB))
; /* then that's OK */
/* if left-hand could be end of nested operator*/
else if(LastSymInOp(iOpSymA))
; /* then that's OK */
else
Result = TRUE;
}
return Result;
}
static int AssertOp(int iOpSymA, int iOpSymB)
{
TOpSym* OpSymA;
TOpSym* OpSymB;
OpSymA = OpSyms[iOpSymA];
OpSymB = OpSyms[iOpSymB];
/* should be no grouping operators left at this point */
if(OpSymMatch(OpSymA, "^.*.$") || OpSymMatch(OpSymB, "^.*.$"))
assert(FALSE);
/* better be looking at final opsym of left side */
else if(!OpSymMatch(OpSymA, "@X?$"))
assert(FALSE);
/* better be looking at first opsym of right side */
else if(!OpSymMatch(OpSymA, "X?@*$"))
assert(FALSE);
return FALSE;
}
/* OpRelation() - return the operator precedence relation between two tokens.
*
* This is the function that embodies all our decisions about
* what the precedence relations between tokens should be in order
* to correctly implement the precedence and associativity that the
* input grammar is asking for.
*/
static int OpRelation(int iOpSymA, int iOpSymB)
{
int Result = ERROR_HANDLE;
int RelChar;
TOpSym* OpSymA;
TOpSym* OpSymB;
assert(iOpSymA >= 0); assert(iOpSymA < NOpSyms);
assert(iOpSymB >= 0); assert(iOpSymB < NOpSyms);
OpSymA = OpSyms[iOpSymA];
OpSymB = OpSyms[iOpSymB];
if(OpRelationError(iOpSymA, OpSymA, iOpSymB, OpSymB))
;
else if(iOpSymA == 0) /* $ on left */
{
if(iOpSymB == 1) /* $ id */
Result = LEFT_HANDLE;
else if(OpSymMatch(OpSymB, "^X@") || OpSymMatch(OpSymB, "^@"))
Result = LEFT_HANDLE;
}
else if(iOpSymB == 0) /* $ on right */
{
if(iOpSymA == 1) /* id $ */
Result = RIGHT_HANDLE;
else if(OpSymMatch(OpSymA, "@X$") || OpSymMatch(OpSymA, "@$"))
Result = RIGHT_HANDLE;
}
else if(iOpSymA == 1) /* id on left */
{
if(OpSymMatch(OpSymB, "X@"))
Result = RIGHT_HANDLE;
}
else if(iOpSymB == 1) /* id on right */
{
if(OpSymMatch(OpSymA, "@X"))
Result = LEFT_HANDLE;
}
/* if it's two sequential tokens of a multi-token operator */
else if(FromSameOperator(iOpSymA, iOpSymB) && iOpSymA+1 == iOpSymB)
Result = MIDDLE_HANDLE;
else if(OpSymMatch(OpSymA, "@*.")) /* any kind of left bracketing opsym on left*/
{
Result = LEFT_HANDLE;
}
else if(OpSymMatch(OpSymB, ".*@")) /* any kind of right bracketing opsym on right*/
{
Result = RIGHT_HANDLE;
}
#if 0
else if(OpSymMatch(OpSymA, "^.*@$")) /* rightmost grouping opsym on left */
{
if(OpSymMatch(OpSymB, ".*@"))
Result = RIGHT_HANDLE;
}
#endif
#if 0
else if(OpSymMatch(OpSymA, ".*@$")) /* rightmost opsym in bracketing op on left*/
{
if(OpSymMatch(OpSymB, ".*@"))
Result = RIGHT_HANDLE;
}
/* else if there is an "operand" on one side or the other*/
else if(iOpSymA == 1 || iOpSymB == 1)
{
/* these rules ensure any operand is reduced immediately */
if(iOpSymA == 1) /* id something */
Result = RIGHT_HANDLE; /* id > all */
else if(iOpSymB == 1) /* something id */
Result = LEFT_HANDLE; /* all < id */
}
/* if left opsym can be viewed as rightmost sym of post-unary op */
// else if(RightEnd(OpSymA))
else if(OpSymMatch(OpSymA, "*X@$"))
Result = RIGHT_HANDLE;
// else if(LeftMostSym(iOpSymA, OpSymA))
else if(OpSymMatch(OpSymA, "^@X"))
// LeftMostSym(iOpSymA, OpSymA))
Result = LEFT_HANDLE;
else if(OpSymMatch(OpSymB, ".X@"))
// else if(RightInterior(iOpSymB, OpSymB))
Result = RIGHT_HANDLE;
else if(LeftEnclosure(iOpSymB, OpSymB))
Result = LEFT_HANDLE;
else if(RightEnclosure(iOpSymA, OpSymA))
Result = RIGHT_HANDLE;
else if(PatCmp(".X", OpSymB)) /* if right operator is unary prefix */
Result = LEFT_HANDLE;
else if(PatCmp("X.", OpSymB)) /* if left operator is unary postfix */
Result = RIGHT_HANDLE;
#endif
else if(AssertOp(iOpSymA, iOpSymB))
assert(FALSE);
else if(OpSymA->Operator->Precedence > OpSymB->Operator->Precedence)
Result = LEFT_HANDLE;
else if(OpSymA->Operator->Precedence < OpSymB->Operator->Precedence)
Result = RIGHT_HANDLE;
else /* else, they have equal precedence */
{
if(OpSymA->Operator->Associativity == TK_LEFT)
Result = RIGHT_HANDLE;
else if(OpSymA->Operator->Associativity == TK_RIGHT)
Result = LEFT_HANDLE;
/* else it's non-associative, so leave it as an error */
}
switch(Result)
{
case LEFT_HANDLE:
RelChar = '<';
break;
case RIGHT_HANDLE:
RelChar = '>';
break;
case MIDDLE_HANDLE:
RelChar = '=';
break;
default:
RelChar = '?';
}
if(Globals.Verbose)
{
/* OpSymStr() overwrites previous result... */
printf(" %s %c ", OpSymStr(OpSymA), RelChar);
printf("%s\n", OpSymStr(OpSymB));
}
return Result;
}
/* FindGroup() - locate the index of a group that contains the given pseudo-symbol
*/
static int FindGroup(int PseudoSym)
{
int iPseudoSym, iGroup;
for(iPseudoSym = 0; FGSyms[iPseudoSym] != PseudoSym; ++iPseudoSym)
assert(iPseudoSym < MaxGroups);
assert(iPseudoSym < MaxGroups);
for(iGroup = 0; iGroup < NGroups; ++iGroup)
if(Groups[iGroup*2] > iPseudoSym)
break;
--iGroup;
assert(iGroup >= 0);
assert(iGroup < NGroups);
return iGroup;
}
/* AddEdge() - add an arrow from one group to another.
*
* Even indices into Edges contain the number of the group this
* edge points to, while the next odd indice contains -1 (NIL)
* or the offset of the next edge in the linked list of edges
* for this group.
*/
static void AddEdge(int FGFrom, int FGTo)
{
int FromGroup, ToGroup;
int* LinkPtr;
int iEdge;
assert(FGFrom != FGTo);
FromGroup = FindGroup(FGFrom);
ToGroup = FindGroup(FGTo);
LinkPtr = &Groups[FromGroup*2 + 1];
iEdge = *LinkPtr;
while(iEdge != -1)
{
assert(iEdge < NEdges);
/* if the desired edge already exists*/
if(Edges[iEdge*2] == FGTo)
return;
else
{
LinkPtr = &Edges[iEdge*2 + 1];
iEdge = *LinkPtr;
}
}
/* do this before LinkPtr becomes invalid! */
*LinkPtr = NEdges;
/* Add new link to end of linked list */
Edges = (int*)realloc(Edges, sizeof(int)*2*(NEdges+1));
assert(Edges != NULL);
Edges[NEdges*2] = ToGroup;
Edges[NEdges*2+1] = -1;
++NEdges;
if(Globals.Dump > 1)
printf("edge from group %d -> %d (NEdges now %d)\n", FromGroup, ToGroup, NEdges);
#if 0
if(0)
{
for(iEdge = 0; iEdge < NEdges; ++iEdge)
printf("[%d] ->%d, next=%d\n", iEdge, Edges[iEdge*2], Edges[iEdge*2+1]);
}
#endif
}
static void CreateEdges(void)
{
int OpSymA, OpSymB;
for(OpSymA = 0; OpSymA < NOpSyms; ++OpSymA)
for(OpSymB = 0; OpSymB < NOpSyms; ++OpSymB)
{
int Relation = OpRelation(OpSymA, OpSymB);
#if 0
printf("Consider edge for (%s %c %s)\n",
OpSymStr(OpSyms[OpSymA]),
(Relation<0)?'<':((Relation>0)?'>':'?'),
OpSymStr(OpSyms[OpSymB]));
#endif
if(Relation == LEFT_HANDLE)
AddEdge(OpSymB|GFLAG, OpSymA);
else if(Relation == RIGHT_HANDLE)
AddEdge(OpSymA, OpSymB|GFLAG);
}
}
typedef struct TNode
{
int Group;
int Edge;
} TNode;
/* GroupInStack() - does this group already exist on the stack?
*/
static
int GroupInStack(TNode* Stack, int Max, int Group)
{
int iStack;
for(iStack=0; iStack < Max; ++iStack)
if(Stack[iStack].Group == Group)
return TRUE;
return FALSE;
}
static int FirstOfGroup(int iFGSym)
{
int iGroup;
int Result = FALSE;
for(iGroup = 0; iGroup < NGroups; ++iGroup)
if(Groups[iGroup*2] == iFGSym)
{
Result = TRUE;
break;
}
return Result;
}
#if 0
static void DumpInternal(void)
{
int iGroup, iFGSym, iEdge;
printf("Groups:\n");
for(iGroup=0; iGroup < NGroups; ++iGroup)
printf(" [%3d] %3d %3d\n", iGroup, Groups[iGroup*2], Groups[iGroup*2+1]);
printf("PseudoSymbols:\n");
for(iFGSym = 0; iFGSym < MaxGroups; ++iFGSym)
printf(" [%3d]%s0x%08X %s(%s)\n",
iFGSym,
(!FirstOfGroup(iFGSym)) ? "_" : " ",
FGSyms[iFGSym],
(FGSyms[iFGSym]&GFLAG)?"g":"f",
OpSymStr(OpSyms[FGSyms[iFGSym]&~GFLAG])
);
printf("Edges:\n");
for(iEdge = 0; iEdge < NEdges; ++iEdge)
printf(" [%3d] Group(%3d) next->%3d\n", iEdge, Edges[iEdge*2], Edges[iEdge*2+1]);
}
#endif
/* FindLongestPath() -
*
*
*/
static
void DumpStack(TNode* Stack, TNode* Node)
{
int iOpSym;
TNode* Rover = Stack;
printf("[%d] ", Node-Stack);
do {
#if 0
printf("Rover->Group=%d\n", Rover->Group);
fflush(stdout);
printf("Groups[Rover->Group*2]=%d\n", Groups[Rover->Group*2]);
fflush(stdout);
printf("FGSyms[Groups[Rover->Group*2]]=%d\n", FGSyms[Groups[Rover->Group*2]]);
fflush(stdout);
#endif
iOpSym = FGSyms[Groups[Rover->Group*2]];
printf("%c%s", (iOpSym&GFLAG)?'g':'f',
OpSymStr(OpSyms[iOpSym&~GFLAG]));
} while(Rover++ != Node);
printf("\n");
}
#if 0
/* TopoOrder() - obtain a list of groups (vertices) in topological order
*/
static
int* TopoOrder()
{
int* Sorted;
int* Start;
int iSorted, iStart;
int* TmpEdges;
int* TmpGroups;
/* make a copy of graph */
TmpEdges = malloc(sizeof(int)*2*NEdges);
assert(TmpEdges != NULL);
TmpGroups =
/* Sorted will contain the nodes (group numbers) in topological order */
Sorted = calloc(NGroups, sizeof(Groups[0]));
assert(Sorted != NULL);
/* Start contains 0 or 1 to indicate with a node (group number) is in the list */
Start = calloc(NGroups, sizeof(Groups[0]));
assert(Start != NULL);
/* Start <- Set of all nodes with no incoming edges */
/* First, assume all nodes are start nodes */
for(iStart=0; iStart < NGroups; ++iStart)
Start[iStart] = 1;
/* Then eliminate the nodes that have incoming edges */
for(iEdge = 0; iEdge < NEdges; ++iEdge)
Start[Edges[iEdge*2]] = 0;
for(iSorted=0; ; ++iSorted)
{
/* locate the next node in Start */
for(iStart = 0; iStart < NGroups; +iStart)
if(Start[iStart])
break;
/* if no more nodes in Start, then we are done! */
if(iStart >= NGroups)
break;
/* remove a node from Start and insert it into Sorted */
Start[iStart] = 0;
Sorted[iSorted] = iStart;
}
}
/* FindLongestPath() - also does cycle detection!
*
* Algorithm stolen from Wikipedia. Brute force turns out to
* be a looooooong wait when you have as many operators as C does.
*/
static
int FindLongestPath(int Group)
{
int MaxPath = 0;
int* LengthTo;
LengthTo = calloc(NGroups, sizeof(int));
assert(LengthTo != NULL);
free(LengthTo);
return MaxPath;
}
static
int FindLongestPath(int Group)
{
int HighWater;
TNode* Stack;
TNode* Node;
Stack = (TNode*)malloc(sizeof(TNode)*MaxGroups*2);
assert(Stack != NULL);
Node = Stack;
//??? Node->Group = Groups[Group*2];
Node->Group = Group;
Node->Edge = Groups[Group*2+1];
HighWater = 0;
printf("group=%d, MaxGroups=%d, Node->Group=%d\n", Group, MaxGroups, Node->Group);
while(Node >= Stack)
{
DumpStack(Stack, Node);
/* if we hit end of linked list for this stacked node */
if(Node->Edge == -1)
{
/* pop stack until we find a node not at end of its list */
while(Node->Edge == -1 && Node >= Stack)
--Node;
}
/* else, push the node pointed to by current edge */
else
{
Group = Edges[Node->Edge*2];
if(GroupInStack(Stack, (Node-Stack)+1, Group))
{
int iStack;
TNode* Rover = Stack;
if(Globals.Dump)
{
DumpInternal();
for(iStack=0; Rover <= Node; ++iStack)
{
fprintf(stdout, "stack[%d] group = %d, edge = %d\n", iStack, Rover->Group, Rover->Edge);
++Rover;
}
}
ErrorExit(ERROR_FAILED_OP_PREC_TABLE,
"Internal error(FindLongestPath() cycle via %d\n"
"Can't create operator precedence table.\n",
Group
);
}
/* ??? is this off by one?*/
assert(Node-Stack < MaxGroups*2);
Node[1].Group = Group;
Node[1].Edge = Groups[Group*2+1];
printf("push group=%d, Edge=%d\n", Group, Groups[Group*2+1]);
/* but first advance in linked list of current topmost node */
Node->Edge = Edges[Node->Edge*2+1];
printf(" previous edge moves to %d\n", Node->Edge);
++Node;
}
if(Node-Stack > HighWater)
HighWater = Node-Stack;
}
printf("HighWater was %d\n", HighWater);
free(Stack);
return HighWater;
}
#endif
/* CalcPrec() - calculate the precedence table, if possible.
*
* The algorithm is taken from:
* "A Note on Computing Precedence Functions",
* The Computer Journal
* Vol 25, No. 3, 1982
* pp. 397-398
* Note that, due to the restricted method we offer for specifying
* operator precedence, we don't have to worry about the '=' relation
* here.
*/
static
void CalcPrec(void)
{
int iOpSym, iOpSymA, iOpSymB, iPrec, iNode;
BITSET* Links;
BITSET* EqLinks;
BITSET Nodes;
BITITER Node;
/* create space to represent our reversed graph */
Links = malloc(2*sizeof(BITSET)*2*NOpSyms);
assert(Links != NULL);
for(iNode=0; iNode < 2*2*NOpSyms; ++iNode)
Links[iNode] = BitSetNew(2*NOpSyms);
EqLinks = Links + 2*NOpSyms;
/* Create representation of backward operator precedence graph. */
for(iOpSymA = 0; iOpSymA < NOpSyms; ++iOpSymA)
for(iOpSymB = 0; iOpSymB < NOpSyms; ++iOpSymB)
{
int Rel = OpRelation(iOpSymA, iOpSymB);
if(Rel == RIGHT_HANDLE) /* fA > gB, so make gB -> fA */
BitSetSet(Links[NOpSyms + iOpSymB], iOpSymA);
else if(Rel == LEFT_HANDLE) /* fA < gB, so make fA -> gB */
BitSetSet(Links[iOpSymA], NOpSyms+iOpSymB);
// else if(Rel == MIDDLE_HANDLE) /* fA = gB, so make gB -- fA*/
// BitSetSet(EqLinks[NOpSyms+iOpSymB], iOpSymA);
}
for(iOpSymA = 0; iOpSymA < NOpSyms; ++iOpSymA)
{
TOpSym* OpSym = OpSyms[iOpSymA];
if(LeftMostSym(iOpSymA, OpSym))
{
for(iOpSymB=iOpSymA+1; FromSameOperator(iOpSymA, iOpSymB); ++iOpSymB)
{
BitSetSet(EqLinks[iOpSymA], iOpSymB+NOpSyms);
BitSetSet(EqLinks[NOpSyms+iOpSymB], iOpSymA);
}
}
}
/* Finally, we can start calculating precedences.
* Start with f$ and g$ and trace the backwards graph from there.
*/
/* create f and g tables, assume everything zero precedence initially */
FGTable = (int*)calloc(NOpSyms*2, sizeof(int));
assert(FGTable != NULL);
Nodes = BitSetNew(NOpSyms*2);
/* set initial set of nodes */
BitSetSet(Nodes, 0);
BitSetSet(Nodes, NOpSyms);
#if 0
for(iOpSym = 1; iOpSym < NOpSyms; ++iOpSym)
{
TOpSym* OpSym = OpSyms[iOpSym];
if(OpSym->Operator->SymCount > 1) /* if multisymbol operator */
{
/* if leftmost opsym with no operand to left */
if(OpSym->ListIndex == 0)
{
BitSetSet(Nodes, iOpSym);
BitSetOr(Nodes, EqLinks[iOpSym]);
}
/* if rightmost opsym with no operand to right */
else if(OpSym->ListIndex == SymbolListCount(OpSym->Operator->List)-1)
{
BitSetSet(Nodes, iOpSym + NOpSyms);
BitSetOr(Nodes, EqLinks[iOpSym+NOpSyms]);
}
}
}
#endif
for(iPrec = 0; iPrec < 2*NOpSyms && BitSetCount(Nodes); ++iPrec)
{
int iOpSym;
BITSET Next;
if(Globals.Dump && Globals.Verbose)
{
printf("[%d] ", iPrec);
Node = BitIterNew(Nodes);
while((iOpSym=BitIterNext(&Node)) != -1)
{
int G=(iOpSym >= NOpSyms);
printf("%c%s ", G?'g':'f', OpSymStr(OpSyms[G?iOpSym-NOpSyms:iOpSym]));
}
printf("\n");
fflush(stdout);
}
Next = BitSetNew(2*NOpSyms); /* Next will contain the next set of nodes */
/* for all nodes in this step of traversal */
Node = BitIterNew(Nodes);
while((iOpSym=BitIterNext(&Node)) != -1)
{
// BITITER Temp;
{
BITITER Temp;
char FG;
FG = (iOpSym / NOpSyms)?'g':'f';
printf("%c%s -> ", FG, OpSymStr(OpSyms[iOpSym%NOpSyms]));
Temp = BitIterNew(Links[iOpSym]);
while((iOpSymA=BitIterNext(&Temp)) != -1)
{
FG = (iOpSymA / NOpSyms)?'g':'f';
printf("%c%s ", FG, OpSymStr(OpSyms[iOpSymA%NOpSyms]));
}
printf("\n ===> ");
Temp = BitIterNew(EqLinks[iOpSym]);
while((iOpSymA=BitIterNext(&Temp)) != -1)
{
FG = (iOpSymA / NOpSyms)?'g':'f';
printf("%c%s ", FG, OpSymStr(OpSyms[iOpSymA%NOpSyms]));
}
printf("\n");
}
/* put it in our next set of nodes */
BitSetOr(Next, Links[iOpSym]);
BitSetOr(Next, EqLinks[iOpSym]);
}
/* update precedence numbers for next set of nodes */
Node = BitIterNew(Next);
while((iOpSym=BitIterNext(&Node)) != -1)
if(FGTable[iOpSym] <= iPrec)
FGTable[iOpSym] = iPrec + 1;
BitSetCopy(Nodes, Next);
BitSetDelete(Next);
}
if(iPrec >= 2*NOpSyms)
ErrorExit(ERROR_FAILED_OP_PREC_TABLE, "Can't happen: Could not create operator precedence table!");
if(Globals.Dump)
{
printf("f/g table for %d operator symbols!\n", NOpSyms);
for(iOpSym = 0; iOpSym < NOpSyms; ++iOpSym)
printf("%10s [%3d] f%3d g%3d\n",
OpSymStr(OpSyms[iOpSym]),
iOpSym, FGTable[iOpSym], FGTable[NOpSyms+iOpSym]);
fflush(stdout);
}
/* Now double-check FTable and GTable. We take the Cartesian
* product of all the operator tokens and, for each pair,
* confirm that FTable and GTable provide the same precedence
* relation as OpRelation() claims it should.
*/
for(iOpSymA = 0; iOpSymA < NOpSyms; ++iOpSymA)
for(iOpSymB = 0; iOpSymB < NOpSyms; ++iOpSymB)
{
int Rel = OpRelation(iOpSymA, iOpSymB);
if(Rel != ERROR_HANDLE)
{
int Disaster = FALSE;
if(Rel == LEFT_HANDLE && FGTable[iOpSymA] >= FGTable[NOpSyms+iOpSymB])
Disaster = TRUE;
else if(Rel == RIGHT_HANDLE && FGTable[iOpSymA] <= FGTable[NOpSyms+iOpSymB])
Disaster = TRUE;
else if(Rel == MIDDLE_HANDLE && FGTable[iOpSymA] != FGTable[NOpSyms+iOpSymB])
Disaster = TRUE;
if(Disaster)
{
fprintf(stderr, "Can't happen: f(%d) g(%d)\n"
"OpRelation()=%d f(%s) = %d g(%s) = %d\n",
iOpSymA, iOpSymB,
Rel, OpSymStr(OpSyms[iOpSymA]), FGTable[iOpSymA],
OpSymStr(OpSyms[iOpSymB]), FGTable[NOpSyms+iOpSymB]);
ErrorExit(ERROR_FAILED_OP_PREC_TABLE, "Can't happen: Could not create correct operator precedence table!");
}
}
}
}
#if 0
/* CalcPrec() - calculate precedence tables.
*
* CalcPrec
* FindGroup()
* FindLongestPath()
* GroupInStack()
*/
static void CalcPrec(void)
{
int iOpSym, iOpSymA, iOpSymB;
FTable = (int*)malloc(sizeof(int)*NOpSyms);
assert(FTable != NULL);
GTable = (int*)malloc(sizeof(int)*NOpSyms);
assert(GTable != NULL);
if(Globals.Dump)
{
DumpInternal();
printf("f/g table for %d operator symbols!\n", NOpSyms);
}
for(iOpSym = 0; iOpSym < NOpSyms; ++iOpSym)
{
FTable[iOpSym] = FindLongestPath(FindGroup(iOpSym));
GTable[iOpSym] = FindLongestPath(FindGroup(iOpSym|GFLAG));
if(Globals.Dump)
printf("%6s [%3d] f%3d g%3d\n",
OpSymStr(OpSyms[iOpSym]),
iOpSym, FTable[iOpSym], GTable[iOpSym]);
}
/* Now double-check FTable and GTable. We take the Cartesian
* product of all the operator tokens and, for each pair,
* confirm that FTable and GTable provide the same precedence
* relation as OpRelation() claims it should.
*/
for(iOpSymA = 0; iOpSymA < NOpSyms; ++iOpSymA)
for(iOpSymB = 0; iOpSymB < NOpSyms; ++iOpSymB)
{
int Rel = OpRelation(iOpSymA, iOpSymB);
if(Rel != ERROR_HANDLE)
{
int Disaster = FALSE;
if(Rel == -1 && FTable[iOpSymA] >= GTable[iOpSymB])
Disaster = TRUE;
else if(Rel == 1 && FTable[iOpSymA] <= GTable[iOpSymB])
Disaster = TRUE;
else if(Rel == 0 && FTable[iOpSymA] != GTable[iOpSymB])
Disaster = TRUE;
if(Disaster)
{//??? need official error code
fprintf(stderr, "Can't happen: f(%d) g(%d)\n"
"OpRelation()=%d f(%s) = %d g(%s) = %d\n",
iOpSymA, iOpSymB,
Rel, OpSymStr(OpSyms[iOpSymA]), FTable[iOpSymA],
OpSymStr(OpSyms[iOpSymB]), GTable[iOpSymB]);
DumpInternal();
exit(-999);
}
}
}
}
#endif
/* OperatorCalcPrec() - calculate precedence function tables.
*
* Here is where we calculate the precedence function tables
* FTable and GTable -- abbreviated forms of the complete operator
* precedence matrix.
*/
void OperatorCalcPrec(void)
{
if(NOpSyms > 0)
{
MaxGroups = NOpSyms * 2; /* that's the worst case # of groups required ??? */
Groups = (int*)malloc(sizeof(int)*MaxGroups*2);
assert(Groups != NULL);
FGSyms = (int*)malloc(sizeof(int)*MaxGroups);
if(Globals.Dump)
printf(" CalcPrec\n");
CalcPrec();
}
}
|
100siddhartha-blacc
|
operator.c
|
C
|
mit
| 43,730
|
/* lr0.c - Code to implement LR(0) parser construction.
*/
#include "globals.h"
#include "lr0.h"
#include "symtab.h"
static void ComputeLR0(TSymbol* NonTerm);
static TItemSet* CreateInitialItems(TSymbol* RootSymbol);
static int StateFromItemSet(TStates* States, TItemSet* Items);
static TItemSet* ItemsNew(TItemSet* Copy);
static void ItemsDelete(TItemSet* Items);
static void ItemsAdd(TItemSet* Items, TITEM Item);
static void ItemsExpand(TItemSet* Items, TSymbol* Symbol);
static TITEM AdvanceItem(TSymbol* NonTerm, TStates* States, int iState, int iItem);
static TSymbol* GetItemSymbol(TSymbol* NonTerm, TStates* States, int iState, int iItem);
static void AddTransition(TStates* States, int State, int ToState, TSymbol* Symbol);
static void ItemsAddAll(TItemSet* Items, TSymbol* NonTerm);
static void DumpLR0(TSymbol* Symbol);
static void CheckLR0(TSymbol* Symbol);
static void PostProcess(TSymbol* RootSymbol, TStates* States);
/* ComputeAllLR0() - compute zero or more LR(0) state machines.
*/
void ComputeAllLR0(void)
{
SymIt NonTerm = SymItNew(Globals.NonTerms);
while(SymbolIterate(&NonTerm))
if(NonTerm.Symbol->OperatorTrigger)
{
ComputeLR0(NonTerm.Symbol);
if(Globals.Dump)
DumpLR0(NonTerm.Symbol);
CheckLR0(NonTerm.Symbol);
}
}
/* EquivTokens() - return true if two symbols are "equivalent".
*
* Equivalent here just means they produce identical transitions in
* every single state.
*/
static
int EquivTokens(TStates* States, TSymbol* Sym1, TSymbol* Sym2)
{
int Result = TRUE;
int iState;
for(iState=0; Result && iState < States->Count; ++iState)
{
TState* State = States->States[iState];
int NextState = -1;
int iTransition;
TTransitions* Transitions;
Transitions = &State->Transitions;
for(iTransition=0; iTransition < Transitions->Count; ++iTransition)
{
TTransition Transition = State->Transitions.Transitions[iTransition];
/* if transition is on either of our symbols */
if(Transition.Symbol == Sym1 || Transition.Symbol == Sym2)
{
/* if first match of a symbol, record its next state */
if(NextState == -1)
NextState = Transition.NextState;
/* else see if the two symbols transit to the same state */
else if(NextState == Transition.NextState)
{
NextState = -1;
break;
}
/* else, two symbols don't match */
else
break;
}
}
if(NextState != -1)
{
Result = FALSE;
break;
}
}
return Result;
}
/* ComputeTokenClasses() - create groups of tokens the DFA sees as equivalent.
*
* create stack of unique operator tokens used by DFA
* while stack not empty
* create new token class
* pop optoken off stack
* for each optoken on stack
* if equiv to this optoken
* add it to this token class
* remove it from stack
*/
static
void ComputeTokenClasses(TStates* States)
{
int TokenClassSize, iTokenClass;
SYMBOLS Stack;
SymbolListDump(stdout, States->OpTokens, ",and");
fprintf(stdout, "\n^^^^^^^^^^^^^ %d unique operator tokens \n", SymbolListCount(States->OpTokens));
/* create our token class array */
TokenClassSize = SymbolListCount(States->OpTokens); /* worst case size */
assert(TokenClassSize > 0);
States->TokenClasses = calloc(TokenClassSize, sizeof(SYMBOLS));
assert(States->TokenClasses != NULL);
Stack = SymbolListCopy(NULL, States->OpTokens);
for(iTokenClass=0; SymbolListCount(Stack); ++iTokenClass)
{
TSymbol* ThisOpToken;
TSymbol* OtherOpToken;
SYMBOLS NewClass = SymbolListCreate();
int iOpToken;
ThisOpToken = SymbolListPop(Stack);
NewClass = SymbolListAdd(NewClass, ThisOpToken);
for(iOpToken=0; iOpToken < SymbolListCount(Stack); ++iOpToken)
{
OtherOpToken = SymbolListGet(Stack, iOpToken);
if(EquivTokens(States, ThisOpToken, OtherOpToken))
{
NewClass = SymbolListAdd(NewClass, OtherOpToken);
SymbolListDelete(Stack, iOpToken);
--iOpToken;
}
}
assert(iTokenClass < TokenClassSize);
States->TokenClasses[iTokenClass] = NewClass;
fprintf(stdout, "TokenClass[%d] = ", iTokenClass);
SymbolListDump(stdout, NewClass, ",and");
fprintf(stdout, "\n");
}
}
static
void CheckLR0(TSymbol* Symbol)
{
int iState, iRule, Dot, iItem, iProdItem, NProdItems, ReduceCount;
TStates* States = Symbol->LR0;
TRule* Rule;
if(Globals.Dump && Globals.Verbose)
Dump("CheckLR0('%s')\n", SymbolStr(Symbol));
for(iState=0; iState < States->Count; ++iState)
{
TState* State = States->States[iState];
TItemSet* Items = &State->ItemSet;
int* ReduceRules;
ReduceRules = calloc(Items->Count, sizeof(int));
assert(ReduceRules != NULL);
/* check for reduce-reduce conflicts */
for(ReduceCount=iItem=0; iItem < Items->Count; ++iItem)
{
iRule = Items->Items[iItem] >> 16;
Dot = Items->Items[iItem] & 0x7FFF;
Rule = Symbol->Rules[iRule];
NProdItems = SymbolListCount(Rule->Symbols);
if(Dot == NProdItems)
{
++ReduceCount;
ReduceRules[iItem] = 1;
}
}
if(ReduceCount > 1)
{
ErrorPrologue(ERROR_REDUCE_REDUCE_CONFLICT);
Error("reduce/reduce conflict in '%s' between:\n", SymbolStr(Symbol));
for(iItem=0; iItem < Items->Count; ++iItem)
if(ReduceRules[iItem])
{
iRule = Items->Items[iItem] >> 16;
Dot = Items->Items[iItem] & 0x7FFF;
Rule = Symbol->Rules[iRule];
NProdItems = SymbolListCount(Rule->Symbols);
Error(" -> ");
for(iProdItem=0; iProdItem < NProdItems; ++iProdItem)
Error("%s ", SymbolStr(SymbolListGet(Rule->Symbols, iProdItem)));
Error("\n");
}
ErrorEpilog(0);
}
/* check for shift-reduce that we can't handle */
free(ReduceRules);
}
}
/* ComputeLR0() - Compute the LR(0) state machine for this nonterminal
*/
static
void ComputeLR0(TSymbol* NonTerm)
{
TItemSet* Items;
int State = 0;
TStates* States = NEW(TStates);
TState* ThisState;
assert(States != NULL);
if(Globals.Verbose)
fprintf(stdout, "Compute LR(0) machine for '%s'\n", SymbolStr(NonTerm));
/* create state 0 */
Items = CreateInitialItems(NonTerm);
StateFromItemSet(States, Items);
ItemsDelete(Items);
/* now process each state (which possibly creates new, unprocessed states) */
for(State = 0; State < States->Count; ++State)
{
SYMBOLS Processed = NULL;
TSymbol* Symbol;
int iItem, jItem, NItems, ToState;
printf("------>state %d/%d\n", State, States->Count);
ThisState = States->States[State]; /* grab next unprocessed state */
NItems = ThisState->ItemSet.Count;
/* find an unprocessed symbol that follows the dot */
for(iItem = 0; iItem < NItems; ++iItem)
if((Symbol=GetItemSymbol(NonTerm, States, State, iItem))!= NULL
&& !SymbolListContains(Processed, Symbol)
)
{
printf(" ------>iItem %d, Symbol=%s\n", iItem, SymbolStr(Symbol));
/* create an empty item list */
Items = ItemsNew(NULL);
for(jItem = iItem; jItem < NItems; ++jItem)
if(GetItemSymbol(NonTerm, States, State, jItem) == Symbol)
ItemsAdd(Items, AdvanceItem(NonTerm, States, State, jItem));
ItemsExpand(Items, NonTerm);
ToState = StateFromItemSet(States, Items);
ItemsDelete(Items);
AddTransition(States, State, ToState, Symbol);
/* remember that we processed this symbol */
Processed = SymbolListAdd(Processed, Symbol);
}
else printf(" ------>iItem %d, [Symbol=%p %s]\n", iItem, Symbol, Symbol?SymbolStr(Symbol):"");
SymbolListDestroy(Processed);
}
PostProcess(NonTerm, States);
ComputeTokenClasses(States);
NonTerm->LR0 = States;
printf("Compute LR(0) is done\n");
}
/* PostProcess() - make another pass over the final list of states.
*
* This is a good time to mark which states are accepting, and to
* add a transition on BLC_EOF to one special state.
*/
static
void PostProcess(TSymbol* RootSymbol, TStates* States)
{
TItemSet* Items;
int iState, jState;
int FinalCount;
TState* State;
/* for each state */
FinalCount = 0;
for(iState = 0; iState < States->Count; ++iState)
{
int iItem, NItems;
int Final;
State = States->States[iState];
NItems = State->ItemSet.Count;
Items = &State->ItemSet;
/* for each item in this state */
Final = TRUE;
for(iItem = 0; iItem < NItems; ++iItem)
{
int iRule, Dot,NProdItems;
TRule* Rule;
iRule = Items->Items[iItem] >> 16;
Dot = Items->Items[iItem] & 0x7FFF;
Rule = RootSymbol->Rules[iRule];
NProdItems = SymbolListCount(Rule->Symbols);
if(Dot >= NProdItems)
State->Accepting = TRUE;
/* every item in the "final" state must look like this:
* expr -> expr . [...]
* If we had faked an initial S -> expr $, then the final
* state would have been the one doing that reduction.
*/
if(Dot != 1 || SymbolListGet(Rule->Symbols, 0) != RootSymbol)
Final = FALSE;
}
if(Final)
{
++FinalCount;
State->Final = Final;
AddTransition(States, iState, 0, SymbolFind(EOFToken));
}
/* see if all inbound transitions are identical */
State->Inbound = -1; /* -1 means no inbound transitions */
for(jState=0; jState < States->Count; ++jState)
{
TState* Other = States->States[jState];
int NTrans = Other->Transitions.Count;
TTransition* Trans = Other->Transitions.Transitions;
int iTrans;
for(iTrans=0; iTrans < NTrans; ++iTrans)
{
}
for(iItem=0; iItem < Items->Count; ++iItem)
{
int iRule, Dot,NProdItems;
TRule* Rule;
}
}
}
// assert(FinalCount == 1);
}
/* CreateInitialItems() - create initial item set.
*
* We create an item set containing one item for each
* rule in the root symbol. For example, if the root
* symbol looks like this:
* E -> '-' E
* | E '-' E
* | TK_ID
* then our item set would be:
* E -> .'-' E
* E -> .E '-' E
* E -> .TK_ID
*
* Note that the initial state cannot be an accepting state
* because E is not allowed to be nullable.
*/
static
TItemSet* CreateInitialItems(TSymbol* RootSymbol)
{
int iRule;
TItemSet* Result = NEW(TItemSet);
assert(Result != NULL);
Result->Count = RootSymbol->NRules;
assert(Result->Count >= 0);
Result->Items = calloc(Result->Count, sizeof(TITEM));
assert(Result->Items != NULL);
for(iRule = 0; iRule < Result->Count; ++iRule)
Result->Items[iRule] = (iRule << 16) | 0;
return Result;
}
/* ItemsNew() - Create a new itemset (possibly a copy of an existing one)
*
*/
static
TItemSet* ItemsNew(TItemSet* Copy)
{
TItemSet* Result;
Result = NEW(TItemSet);
if(Copy)
{
Result->Count = Copy->Count;
if(Result->Count)
{
Result->Items = calloc(Copy->Count, sizeof(TITEM));
memcpy(Result->Items, Copy->Items, Copy->Count * sizeof(TITEM));
}
}
return Result;
}
static
void ItemsDelete(TItemSet* Items)
{
if(Items->Items)
free(Items->Items);
free(Items);
}
/* ItemsExpand() - perform closure on this item set.
*
* Suppose there is an item whose dot is followed by a non-terminal:
* E -> '(' E ')' .E
* In that case, for every production of the form E -> X, we must add
* an item of E -> .X
*/
static
void ItemsExpand(TItemSet* Items, TSymbol* NonTerm)
{
int iItem, iRule, iDot, NProdItems;
TRule* Rule;
TSymbol* Symbol;
for(iItem = 0; iItem < Items->Count; ++iItem)
{
iRule = Items->Items[iItem] >> 16;
assert(iRule >= 0 && iRule < NonTerm->NRules);
Rule = NonTerm->Rules[iRule];
NProdItems = SymbolListCount(Rule->Symbols);
iDot = Items->Items[iItem] & 0x7FFF;
assert(iDot >= 0 && iDot <= NProdItems);
/* if dot is not after final symbol on rhs */
if(iDot < NProdItems)
{
Symbol = SymbolListGet(Rule->Symbols, iDot);
if(Symbol == NonTerm)
{
ItemsAddAll(Items, NonTerm);
break;
}
}
}
}
/* ItemsAddAll() - add all rules of nonterminal as items.
*
* For example, if E -> '-' E | E '-' E | '(' E ')'
* then we would create items:
* E -> . '-' E
* E -> . E '-' E
* E -> . '(' E ')'
*/
static
void ItemsAddAll(TItemSet* Items, TSymbol* NonTerm)
{
int iRule;
for(iRule = 0; iRule < NonTerm->NRules; ++iRule)
ItemsAdd(Items, iRule << 16);
}
static
void ItemsDump(TItemSet* Items)
{
int iItem;
fprintf(stdout, "Dump TItemSet, Count=%d\n", Items->Count);
for(iItem = 0; iItem < Items->Count; ++iItem)
{
fprintf(stdout, " [%2d] 0x%08X\n", iItem, Items->Items[iItem]);
}
}
/* ItemsAdd() - add an item to an item set.
*
* Since this is a set, the new item is not added if it is
* already present.
*/
static
void ItemsAdd(TItemSet* Items, TITEM Item)
{
int iItem;
if(Item != -1) /* -1 means no item to add */
{
DumpVerbose("ItemsAdd(0x%08X) rule=%d, dot=%d\n", Item, Item >> 16, Item & 0x7FFF);
for(iItem = 0; iItem < Items->Count; ++iItem)
if(Items->Items[iItem] == Item)
break;
if(iItem >= Items->Count)
{
Items->Items = realloc(Items->Items, (++Items->Count)*sizeof(TITEM));
Items->Items[iItem] = Item;
}
}
if(Globals.Dump && Globals.Verbose)
ItemsDump(Items);
}
static
TITEM ItemFromItemPos(TStates* States, int iState, int iItem)
{
TItemSet* Items;
TITEM Item;
assert(iState >= 0);
assert(iState < States->Count);
assert(States->States[iState] != NULL);
Items = &States->States[iState]->ItemSet;
assert(iItem >= 0);
assert(iItem < Items->Count);
Item = Items->Items[iItem];
DumpVerbose("ItemFromItemPos(state=%d, iItem=%d)=0x%08X\n", iState, iItem, Item);
return Item;
}
/* GetItemSymbol() - return symbol following dot in an item.
*
* Suppose a state contains these items:
* E -> '(' E ')'.
* E -> '(' E ')' .E
* E -> .'-' E
* For this state, GetItemSymbol(..., 0) would return NULL,
* GetItemSymbol(..., 1) would return the TSymbol* for 'E',
* and GetItemSymbol(...,2) would return the TSymbol* for '-'.
*/
static
TSymbol* GetItemSymbol(TSymbol* NonTerm, TStates* States, int iState, int iItem)
{
TItemSet* Items;
TITEM Item;
int iRule, iPos;
TRule* Rule;
TSymbol* Result;
assert(iState >= 0);
assert(iState < States->Count);
assert(States->States[iState] != NULL);
Items = &States->States[iState]->ItemSet;
assert(iItem >= 0);
assert(iItem < Items->Count);
Item = Items->Items[iItem];
iRule = Item >> 16;
iPos = Item & 0x7FFF;
Rule = NonTerm->Rules[iRule];
/* returns NULL if iPos past end */
Result = SymbolListGet(Rule->Symbols, iPos);
return Result;
}
/* StateFromItemSet() - return # of state associated with an item set.
*
* Given an item set, this function locates an existing state that
* has that identical item set. If no such state exists, it is created
* and added to the end. The return value is the (zero-based) integer
* offset of the state.
*/
static int ItemCmp(const void* A, const void* B)
{ return *(const int*)A - *(const int*)B; }
static
int StateFromItemSet(TStates* States, TItemSet* Items)
{
TState* NewState;
int iItem, iState;
if(Items->Count <= 0)
return -1;
/* sort item lists for ease of comparing */
qsort(Items->Items, (size_t)Items->Count, sizeof(TITEM), ItemCmp);
for(iState = 0; iState < States->Count; ++iState)
if(States->States[iState]->ItemSet.Count == Items->Count)
{
for(iItem = 0; iItem < Items->Count; ++iItem)
if(States->States[iState]->ItemSet.Items[iItem] != Items->Items[iItem])
break;
/* if an existing state matches */
if(iItem >= Items->Count)
return iState;
}
/* have to create a new state */
States->States = realloc(States->States, (States->Count+1)*sizeof(TState*));
assert(States->States != NULL);
NewState = NEW(TState);
assert(NewState != NULL);
NewState->ItemSet.Count = Items->Count;
NewState->ItemSet.Items = calloc(Items->Count, sizeof(TITEM));
assert(NewState->ItemSet.Items != NULL);
memcpy(NewState->ItemSet.Items, Items->Items, Items->Count*sizeof(TITEM));
States->States[States->Count] = NewState;
if(Globals.Dump)
{
int iItem;
fprintf(stdout, "Create new state %d\n", States->Count);
for(iItem = 0; iItem < NewState->ItemSet.Count; ++iItem)
{
TITEM Item = NewState->ItemSet.Items[iItem];
int iRule = Item >> 16;
int Dot = Item & 0x7FFF;
fprintf(stdout, " (0x%08X) rule %d, dot=%d\n", Item, iRule, Dot);
}
}
return States->Count++;
}
/* AdvanceItem() - Advance the item's dot!
*
* Suppose we have an item like this:
* E -> '(' .E ')'
* Then AdvanceItem() would return this item:
* E -> '(' E .')'
*
* An attempt to advance past the last position returns -1.
*/
static
TITEM AdvanceItem(TSymbol* NonTerm, TStates* States, int iState, int iItem)
{
TITEM Item;
int iRule, DotPos;
TRule* Rule;
Item = ItemFromItemPos(States, iState, iItem);
iRule = Item >> 16;
DotPos = Item & 0x7FFF;
assert(iRule >= 0);
assert(iRule < NonTerm->NRules);
Rule = NonTerm->Rules[iRule];
assert(DotPos >= 0);
assert(DotPos <= SymbolListCount(Rule->Symbols));
if(DotPos >= SymbolListCount(Rule->Symbols))
Item = -1;
else
Item = (iRule << 16) | ++DotPos;
if(Globals.Dump)
fprintf(stdout, "AdvanceItem(state=%d, item=%d) [rule %d, dot %d] returns 0x%08X\n",
iState, iItem, iRule, DotPos-1, Item);
return Item;
}
/* AddTransition() - add a transition to a state.
*
* A transition consists of a symbol and a destination state.
* It is benign to attempt to add a transition that already
* exists in the given state. If Symbol is actually a non-terminal
* representing a list of operators, then we "explode" that list
* here, and act on the entire list.
*
* As a side-effect, this function also (may) add Symbol to the States
* OpTokens array of unique operator tokens seen.
*/
static
void AddTransition(TStates* States, int iState, int ToState, TSymbol* Symbol)
{
int iTransition;
TState* State;
TTransition Transition = {0};
TTransitions* Transitions;
SYMBOLS List = SymbolListAdd(NULL, Symbol);
SymIt ThisSym;
if(ToState == -1)
return;
if(Globals.Dump)
fprintf(stdout, "AddTransition from %d -> %d on symbol '%s'\n",
iState, ToState, SymbolStr(Symbol));
/* "explode" Symbol if necessary */
// if(SymbolIsOpSyms(Symbol))
// ??? TODO just copy list
if(Symbol->OpAbbrev)
List = SymbolGetAllSymbols(Symbol);
else
List = SymbolListAdd(NULL, Symbol);
ThisSym = SymItNew(List);
while(SymbolIterate(&ThisSym))
{
Symbol = ThisSym.Symbol;
States->OpTokens = SymbolListAddUnique(States->OpTokens, Symbol);
State = States->States[iState];
Transitions = &State->Transitions;
for(iTransition=0; iTransition < Transitions->Count; ++iTransition)
{
Transition = Transitions->Transitions[iTransition];
if(Transition.Symbol == Symbol && Transition.NextState == ToState)
break;
}
/* if transition does not already exist */
if(iTransition >= Transitions->Count)
{
Transition.NextState = ToState;
Transition.Symbol = Symbol;
Transitions->Transitions = realloc(Transitions->Transitions, (State->Transitions.Count+1)*sizeof(TTransition));
Transitions->Transitions[Transitions->Count++] = Transition;
}
}
}
/* DumpLR0() - dump the LR(0) machine associated with a given symbol.
*/
static
void DumpLR0(TSymbol* Symbol)
{
int iState;
TStates* States = Symbol->LR0;
assert(States != NULL);
fprintf(stdout, "LR(0) machine for '%s', %d States\n", SymbolStr(Symbol), States->Count);
for(iState=0; iState < States->Count; ++iState)
{
TState* State = States->States[iState];
TItemSet* Items = &State->ItemSet;
int iItem, iTrans;
int HasShift = FALSE;
/* first, calculate whether this is an accepting state or not */
State->Accepting = FALSE;
for(iItem=0; iItem < Items->Count; ++iItem)
{
int iRule, Dot,NProdItems;
TRule* Rule;
iRule = Items->Items[iItem] >> 16;
Dot = Items->Items[iItem] & 0x7FFF;
Rule = Symbol->Rules[iRule];
NProdItems = SymbolListCount(Rule->Symbols);
if(Dot >= NProdItems)
State->Accepting = TRUE;
else
HasShift = TRUE;
if(State->Accepting && HasShift)
break;
}
fprintf(stdout, "State %d, %d items %s %s\n",
iState, Items->Count,
State->Accepting?(HasShift?"AMBIGUOUS":"ACCEPTING"):"",
State->Final?"FINAL":"");
for(iItem=0; iItem < Items->Count; ++iItem)
{
int iRule, Dot, iProdItem, NProdItems;
TRule* Rule;
iRule = Items->Items[iItem] >> 16;
Dot = Items->Items[iItem] & 0x7FFF;
Rule = Symbol->Rules[iRule];
NProdItems = SymbolListCount(Rule->Symbols);
fprintf(stdout, "%s %s -> ",
(Dot >= NProdItems) ? "A" : " ",
SymbolStr(Symbol));
for(iProdItem=0; iProdItem < NProdItems; ++iProdItem)
fprintf(stdout, "%s%s ",
(iProdItem == Dot)?".":"",
SymbolStr(SymbolListGet(Rule->Symbols, iProdItem)));
fprintf(stdout, "%s\n", (Dot == NProdItems) ? "." : "");
}
for(iTrans=0; iTrans < State->Transitions.Count; ++iTrans)
{
fprintf(stdout, " [%s]->%d\n",
SymbolStr(State->Transitions.Transitions[iTrans].Symbol),
State->Transitions.Transitions[iTrans].NextState);
}
}
}
|
100siddhartha-blacc
|
lr0.c
|
C
|
mit
| 26,126
|
/* map.c - simple, highly-limited container class.
*
* We assume nothing is ever deleted, and caller supplies (and retains)
* storage for all keys and objects to be placed in a map.
*/
#include "map.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#define LOADFACTOR (8)
#define CHUNKSIZE (128)
static
size_t Primes[] =
{
13, 59, 97, 257, 499, 977, 2083, 4019, 8011, 9973
};
#define NPRIMES (sizeof(Primes)/sizeof(Primes[0]))
typedef struct TMapLink
{
struct TMapLink* Next;
void* Key;
size_t KeyLen;
void* Value;
} TMapLink;
typedef struct TMap
{
size_t HashTableSize;
TMapLink** HashTable;
TMapCompare Compare;
int NLinks;
} TMap;
/* NewLink() - allocate a new TMapLink structure.
*
* Some insane impulse towards optimization leads me to make a
* chunk allocator, even though I waste memory and CPU with abandon
* elsewhere.
*/
TMapLink* NewLink(void)
{
TMapLink* Result;
static TMapLink* FreeList = NULL;
if(FreeList == NULL)
{
int iLink;
FreeList = (TMapLink*)calloc(CHUNKSIZE, sizeof(TMapLink));
assert(FreeList != NULL);
for(iLink = 0; iLink < (CHUNKSIZE-1); ++iLink)
FreeList[iLink].Next = &FreeList[iLink+1];
/* calloc() already ensured final link.Next is zero (NULL) */
}
Result = FreeList;
FreeList = FreeList->Next;
return Result;
}
int DefCmp(void* A, size_t ALen, void* B, size_t BLen)
{
int Result = 0;
if(ALen == BLen)
Result = memcmp(A, B, ALen);
return Result;
}
MAP MapCreate(TMapCompare Compare)
{
TMap* Result;
Result = (TMap*)calloc(1, sizeof(TMap));
assert(Result != NULL);
if(Compare == NULL)
Compare = DefCmp;
Result->Compare = Compare;
Result->HashTableSize = Primes[0];
Result->HashTable = (TMapLink**)calloc(Result->HashTableSize, sizeof(TMapLink*));
assert(Result->HashTable != NULL);
return (MAP)Result;
}
size_t FindBucket(TMap* Map, void* Key, size_t KeyLen)
{
size_t Hash = 0;
char* Rover;
if(KeyLen == 0) /* if key is really an int */
{
Rover = (char*)&Key;
KeyLen = sizeof(void*);
}
else
Rover = (char*)Key;
while(KeyLen--)
Hash = (Hash << 5) ^ *Rover++;
return Hash % Map->HashTableSize;
}
void* MapFind(MAP Handle, void* Key, size_t KeyLen)
{
size_t Bucket;
TMap* Map;
TMapLink* Rover;
void* Result = NULL;
Map = (TMap*)Handle;
assert(Map != NULL);
Bucket = FindBucket(Map, Key, KeyLen);
Rover = Map->HashTable[Bucket];
while(Rover != NULL)
if(!Map->Compare(Rover->Key, Rover->KeyLen, Key, KeyLen))
{
Result = Rover->Value;
break;
}
else
Rover = Rover->Next;
return Result;
}
void* MapAdd(MAP Handle, void* Key, size_t KeyLen, void* Value)
{
size_t Bucket;
TMap* Map;
TMapLink* Rover;
void* Result = NULL;
TMapLink* Target;
Map = (TMap*)Handle;
assert(Map != NULL);
assert(Map->HashTableSize > 0);
Bucket = FindBucket(Map, Key, KeyLen);
Rover = Map->HashTable[Bucket];
while(Rover != NULL)
if(!Map->Compare(Rover->Key, Rover->KeyLen, Key, KeyLen))
{
Result = Rover->Value;
break;
}
else
Rover = Rover->Next;
/* if this key already in use */
if(Result)
Target = Rover;
else
{
Result = Value;
Target = NewLink();
Target->Next = Map->HashTable[Bucket];
Map->HashTable[Bucket] = Target;
++Map->NLinks;
}
if((Map->NLinks / Map->HashTableSize) > LOADFACTOR)
{
/* ??? enlarge hash table */
}
Target->Key = Key;
Target->KeyLen = KeyLen;
Target->Value = Value;
return Result;
}
|
100siddhartha-blacc
|
map.c
|
C
|
mit
| 4,357
|
#ifndef SYMBOL_H_
# include "symbol.h"
#endif
#ifndef SYMLIST_H_
# include "symlist.h"
#endif
#define SYMTAB_H_ // ???TODO: temporary hack until symbols.h integrated!
#ifndef GLOBALS_H_
# include "globals.h"
#endif
/* constants
************************************************************************/
#define HASH_TABLE_SIZE (199) /* use prime number so modulo is decent hash */
/* type definitions
************************************************************************/
struct TSymbol;
struct TSymAtom;
typedef struct TSymAtom /* underlying atomic object */
{
TToken Name; /* convenience: token of first instance */
int BitFlags;
SYMLIST Instances; /* list of all instances of this atom */
} TSymAtom;
typedef struct TSymbol
{
TToken Name; /* Token associated with this instance */
TSymAtom* Atom;
} TSymbol;
enum
{
SYM_TERMINAL = 0x0001,
SYM_LEFTRECURSIVE = 0x0002,
SYM_FIRSTFOLLOWCLASH = 0x0004,
SYM_NULLABLE = 0x0008,
SYM_USEDINRULE = 0x0010,
SYM_SIMPLE = 0x0020, /* symbol derives only terminals */
SYM_EMPTY = 0x0040, /* symbol derives nothing */
};
/* file scope variables
************************************************************************/
static SYMLIST HashTable[HASH_TABLE_SIZE];
/* internal function declarations
************************************************************************/
static SYMBOL SymbolNew(TToken Token, int Terminal);
static TSymAtom* SymAtomFind(TToken Token, int Create);
static void SymAtomBitSet(TSymAtom* Atom, int Bit);
/* external function definitions
************************************************************************/
/* SymbolNewNonTerm() - create a new non-terminal data structure.
*
* We assume someone else has already verified that no symbol
* with this name already exists.
***********************************************************************/
SYMBOL SymbolNewNonTerm(TToken Token)
{
SYMBOL Result;
Result = SymbolNew(Token, FALSE);
Globals.NonTerms = SymListAdd(Globals.NonTerms, Result);
return Result;
}
/* SymbolNewTerm() - create a new terminal data structure.
*
* We assume someone else has already verified that no symbol
* with this name already exists.
***********************************************************************/
SYMBOL SymbolNewTerm(TToken Token)
{
TSymbol* Result;
if(SymbolFind(Token, FALSE))
ErrorExit(ERROR_TERM_ALREADY_DEFINED, "Terminal already defined: '%.*s'\n",
Token.TextLen, Token.Text);
Result = SymbolAdd(Token, SYM_TERMINAL);
assert(Result != NULL);
Globals.Terminals = SymbolListAdd(Globals.Terminals, Result);
/* Bit of a hack, but we'll set ->First here.
* the FIRST() set of a terminal is just the terminal
*/
Result->First = SymbolListAdd(Result->First, Result);
return (SYMBOL)Result;
}
TSymbol* SymbolNewTerm(TToken Token)
{
TSymbol* Result;
if(SymbolFind(Token))
ErrorExit(ERROR_TERM_ALREADY_DEFINED, "Terminal already defined: '%.*s'\n",
Token.TextLen, Token.Text);
Result = SymbolAdd(Token, SYM_TERMINAL);
assert(Result != NULL);
Globals.Terminals = SymbolListAdd(Globals.Terminals, Result);
/* Bit of a hack, but we'll set ->First here.
* the FIRST() set of a terminal is just the terminal
*/
Result->First = SymbolListAdd(Result->First, Result);
return Result;
}
/* SymbolNew() - return a new symbol instance.
*/
static SYMBOL SymbolNew(TToken Token, int Terminal)
{
TSymbol* Symbol = NEW(TSymbol);
assert(Symbol != NULL);
Symbol->Name = Token;
Symbol->Atom = SymAtomFind(Token, TRUE);
/* if symbol already existed */
if(SymListCount(Symbol->Atom->Instances) == 0)
assert(!Terminal == !SymAtomBitGet(Symbol->Atom, SYM_TERMINAL));
else if(Terminal)
SymAtomBitSet(Symbol->Atom, SYM_TERMINAL);
/* add this new instance to atom's list of instances */
Symbol->Atom->Instances = SymListPush(Symbol->Atom->Instances, Symbol);
return (SYMBOL)Symbol;
}
/* internal functions
************************************************************************/
/* Hash() - hash a name (from a TToken).
*
* A simple XOR hash plus module the prime table size.
************************************************************/
static size_t Hash(const char* Name, size_t Len)
{
size_t Result = Len;
while(Len-- > 0)
Result = (Result << 5) ^ *Name++;
return Result % HASH_TABLE_SIZE;
}
/* SymAtomRef() - create/locate a symbol atom.
*
* A TSymAtom contains the symbol attributes that are the same
* across all instances of that symbol.
***************************************************************/
static TSymAtom* SymAtomFind(TToken Token, int Create)
{
size_t Bucket = Hash(Token.Text, Token.TextLen);
TSymAtom* Atom = NULL;
SYMLIST SymList;
TSymbol* Instance;
SymList = HashTable[Bucket];
Instance = (TSymbol*)SymbolListFind(SymList, Token);
if(Instance) /* if atom already exists */
Atom = Instance->Atom;
else if(Create) /* if caller wants us to create it */
{
Atom = NEW(TSymAtom);
assert(Atom);
Atom->Name = Token;
}
return Atom;
}
static void SymAtomBitSet(TSymAtom* Atom, int Bit)
{
Atom->BitFlags |= Bit;
}
|
100siddhartha-blacc
|
symbol.c
|
C
|
mit
| 6,005
|
#ifndef HTML_H_
#define HTML_H_
void Html(FILE* Output);
#endif
|
100siddhartha-blacc
|
html.h
|
C
|
mit
| 75
|
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef enum { false , true } bool;
/* actions */
typedef enum {
S, /* shift */
R, /* reduce */
A, /* accept */
E1, /* error: missing right parenthesis */
E2, /* error: missing operator */
E3, /* error: unbalanced right parenthesis */
E4 /* error: invalid function argument */
} actEnum;
/* tokens */
typedef enum {
/* operators */
tAdd, /* + */
tSub, /* - */
tMul, /* * */
tDiv, /* / */
tPow, /* ^ (power) */
tUmi, /* - (unary minus) */
tFact, /* f(x): factorial */
tPerm, /* p(n,r): permutations, n objects, r at a time */
tComb, /* c(n,r): combinations, n objects, r at a time */
tComa, /* comma */
tLpr, /* ( */
tRpr, /* ) */
tEof, /* end of string */
tMaxOp, /* maximum number of operators */
/* non-operators */
tVal /* value */
} tokEnum;
tokEnum tok; /* token */
double tokval; /* token value */
#define MAX_OPR 50
#define MAX_VAL 50
char opr[MAX_OPR]; /* operator stack */
double val[MAX_VAL]; /* value stack */
int oprTop, valTop; /* top of operator, value stack */
bool firsttok; /* true if first token */
char parseTbl[tMaxOp][tMaxOp] = {
/* stk ------------------ input ------------------------ */
/* + - * / ^ M f p c , ( ) $ */
/* -- -- -- -- -- -- -- -- -- -- -- -- -- */
/* + */ { R, R, S, S, S, S, S, S, S, R, S, R, R },
/* - */ { R, R, S, S, S, S, S, S, S, R, S, R, R },
/* * */ { R, R, R, R, S, S, S, S, S, R, S, R, R },
/* / */ { R, R, R, R, S, S, S, S, S, R, S, R, R },
/* ^ */ { R, R, R, R, S, S, S, S, S, R, S, R, R },
/* M */ { R, R, R, R, R, S, S, S, S, R, S, R, R },
/* f */ { R, R, R, R, R, R, R, R, R, R, S, R, R },
/* p */ { R, R, R, R, R, R, R, R, R, R, S, R, R },
/* c */ { R, R, R, R, R, R, R, R, R, R, S, R, R },
/* , */ { R, R, R, R, R, R, R, R, R, R, R, R, E4},
/* ( */ { S, S, S, S, S, S, S, S, S, S, S, S, E1},
/* ) */ { R, R, R, R, R, R, E3, E3, E3, R, E2, R, R },
/* $ */ { S, S, S, S, S, S, S, S, S, E4, S, E3, A }
};
int error(char *msg) {
printf("error: %s\n", msg);
return 1;
}
int gettok(void) {
static char str[82];
static tokEnum prevtok;
char *s;
/* scan for next symbol */
if (firsttok) {
firsttok = false;
prevtok = tEof;
gets(str);
if (*str == 'q') exit(0);
s = strtok(str, " ");
} else {
s = strtok(NULL, " ");
}
/* convert symbol to token */
if (s) {
switch(*s) {
case '+': tok = tAdd; break;
case '-': tok = tSub; break;
case '*': tok = tMul; break;
case '/': tok = tDiv; break;
case '^': tok = tPow; break;
case '(': tok = tLpr; break;
case ')': tok = tRpr; break;
case ',': tok = tComa; break;
case 'f': tok = tFact; break;
case 'p': tok = tPerm; break;
case 'c': tok = tComb; break;
default:
tokval = atof(s);
tok = tVal;
break;
}
} else {
tok = tEof;
}
/* check for unary minus */
if (tok == tSub) {
if (prevtok != tVal && prevtok != tRpr) {
tok = tUmi;
}
}
prevtok = tok;
return 0;
}
int shift(void) {
if (tok == tVal) {
if (++valTop >= MAX_VAL)
return error("val stack exhausted");
val[valTop] = tokval;
} else {
if (++oprTop >= MAX_OPR) return
error("opr stack exhausted");
opr[oprTop] = (char)tok;
}
if (gettok()) return 1;
return 0;
}
double fact(double n) {
double i, t;
for (t = 1, i = 1; i <= n; i++)
t *= i;
return t;
}
int reduce(void) {
switch(opr[oprTop]) {
case tAdd:
/* apply E := E + E */
if (valTop < 1) return error("syntax error");
val[valTop-1] = val[valTop-1] + val[valTop];
valTop--;
break;
case tSub:
/* apply E := E - E */
if (valTop < 1) return error("syntax error");
val[valTop-1] = val[valTop-1] - val[valTop];
valTop--;
break;
case tMul:
/* apply E := E * E */
if (valTop < 1) return error("syntax error");
val[valTop-1] = val[valTop-1] * val[valTop];
valTop--;
break;
case tDiv:
/* apply E := E / E */
if (valTop < 1) return error("syntax error");
val[valTop-1] = val[valTop-1] / val[valTop];
valTop--;
break;
case tUmi:
/* apply E := -E */
if (valTop < 0) return error("syntax error");
val[valTop] = -val[valTop];
break;
case tPow:
/* apply E := E ^ E */
if (valTop < 1) return error("syntax error");
val[valTop-1] = pow(val[valTop-1], val[valTop]);
valTop--;
break;
case tFact:
/* apply E := f(E) */
if (valTop < 0) return error("syntax error");
val[valTop] = fact(val[valTop]);
break;
case tPerm:
/* apply E := p(N,R) */
if (valTop < 1) return error("syntax error");
val[valTop-1] = fact(val[valTop-1])/fact(val[valTop-1]-val[valTop]);
valTop--;
break;
case tComb:
/* apply E := c(N,R) */
if (valTop < 1) return error("syntax error");
val[valTop-1] = fact(val[valTop-1])/
(fact(val[valTop]) * fact(val[valTop-1]-val[valTop]));
valTop--;
break;
case tRpr:
/* pop () off stack */
oprTop--;
break;
}
oprTop--;
return 0;
}
int parse(void) {
printf("\nenter expression (q to quit):\n");
/* initialize for next expression */
oprTop = 0; valTop = -1;
opr[oprTop] = tEof;
firsttok = true;
if (gettok()) return 1;
while(1) {
/* input is value */
if (tok == tVal) {
printf("shift value\n");
/* shift token to value stack */
if (shift()) return 1;
continue;
}
printf("tok=%d, oprTop=%d, opr[OprTop]=%d\n", tok, oprTop, opr[oprTop]);
printf("%d\n", parseTbl[opr[oprTop]][tok]);
/* input is operator */
switch(parseTbl[opr[oprTop]][tok]) {
case R:
printf("reduce\n");
if (reduce()) return 1;
break;
case S:
printf("shift\n");
if (shift()) return 1;
break;
case A:
printf("accept\n");
/* accept */
if (valTop != 0) return error("syntax error");
printf("value = %f\n", val[valTop]);
return 0;
case E1:
return error("missing right parenthesis");
case E2:
return error("missing operator");
case E3:
return error("unbalanced right parenthesis");
case E4:
return error("invalid function argument");
default:
printf("can't happen!\n");
}
}
}
int main(void) {
while(1) parse();
return 0;
}
|
100siddhartha-blacc
|
niemann.c
|
C
|
mit
| 7,884
|
#define A a, b
int A;
void f()
{
switch(A)
{
default: ;
}
}
|
100siddhartha-blacc
|
foo.c
|
C
|
mit
| 109
|
/* generate.c - code generation functions.
*
*/
#include "generate.h"
#include "symtab.h"
#include "globals.h"
/* MINRANGE - minimum sequential run of tokens we will use as a range. */
#define MINRANGE (4)
static
void IntAdd(INTVECTOR* This, int Add)
{
int NewSize;
NewSize = This->Size + 1;
This->v = (int*)realloc(This->v, NewSize*sizeof(int));
This->v[This->Size] = Add;
This->Size = NewSize;
}
static
int IntGet(INTVECTOR* This, int Offset)
{
assert(Offset >= 0);
assert(Offset < This->Size);
return This->v[Offset];
}
static
void GrowOpcodes(TParseTables* Tables, size_t Size)
{
if(Tables->OpcodeSize < Size)
{
if(Tables->Opcodes == NULL)
Tables->Opcodes = calloc(Size, sizeof(BLC_OPCODE));
else if(Size > Tables->OpcodeSize)
Tables->Opcodes = realloc(Tables->Opcodes, sizeof(BLC_OPCODE)*Size);
assert(Tables->Opcodes != NULL);
Tables->OpcodeSize = Size;
}
assert(Size <= Tables->OpcodeSize);
}
static
size_t Store16(TParseTables* Tables, size_t IP, int Value)
{
assert(Tables != NULL);
GrowOpcodes(Tables, IP+2);
Tables->Opcodes[IP++] = (unsigned char)(Value & 0x0FF);
Tables->Opcodes[IP++] = (unsigned char)((Value>>8) & 0x0FF);
return IP;
}
static
size_t Store8(TParseTables* Tables, size_t IP, int Value)
{
assert(Tables != NULL);
assert(Value < 0x0FF);
GrowOpcodes(Tables, IP+1);
Tables->Opcodes[IP++] = (unsigned char)(Value & 0x0FF);
return IP;
}
static
size_t StoreStr(TParseTables* Tables, size_t IP, const char* Str)
{
size_t Len = strlen(Str)+1;
GrowOpcodes(Tables, IP+Len);
while(Len > 0)
{
Tables->Opcodes[IP++] = *Str++;
--Len;
}
return IP;
}
/* TSelect - structure for grouping tokens by destination rule
*/
typedef struct TSelRange
{
struct TSelRange* Next;
int Start;
int End;
} TSelRange;
typedef struct TSelect
{
int Rule; /* rule# (as returned by RuleAdd()) */
int MaxRange; /* biggest sequential run of tokens */
int NRanges;
TSelRange* Ranges;
int Count; /* current count of tokens */
INTVECTOR Tokens; /* the actual token values */
} TSelect;
/* SelectNew() - allocate array of TSelect structures.
*/
static
TSelect* SelectNew(int Size)
{
TSelect* Result;
Result = calloc(Size, sizeof(TSelect));
assert(Result != NULL);
return Result;
}
static
void SelectDestroy(TSelect* Table, int Size)
{
int iSelect;
for(iSelect=0; iSelect < Size; ++iSelect)
{
TSelRange* RangeRover;
TSelRange* Temp;
TSelect* Select;
Select = Table + iSelect;
for(RangeRover=Select->Ranges; RangeRover; )
{
Temp = RangeRover->Next;
free(RangeRover);
RangeRover = Temp;
}
free(Table[iSelect].Tokens.v);
}
free(Table);
}
/* SelectAdd() - add a new rule/token pair to the table.
*
* Given a table (array) of TSelect structures, we either
* discover that the rule already exists in the table and
* add this token to its Tokens (symbol list), or else we
* add this rule to the table and then do the same.
*
* The caller is responsible for making sure the table is
* big enough that a new rule can be added to the end.
*/
static
int SelectAdd(TSelect* Table, int Size, int Rule, TSymbol* Token)
{
int iSelect;
int NewSize = Size;
for(iSelect=0; iSelect < Size; ++iSelect)
if(Table[iSelect].Rule == Rule)
break;
if(iSelect >= Size)
{
Table[iSelect].Rule = Rule;
++NewSize;
}
IntAdd(&Table[iSelect].Tokens, Token->Value);
return NewSize;
}
/* SelectAddRange() - add range info to a selection set.
*
* This structure basically indicates there is a range of
* sequential token values in the selection set. Ranges
* are maintained in a linked list in order of range size,
* with the biggest range at the front.
*/
static
void SelectAddRange(TSelect* Select, int Start, int End)
{
TSelRange** Rover;
TSelRange* New;
int Size = (End - Start) + 1;
printf("SelectAddRange(Start=%d, End=%d)\n", Start, End);
// assert(Start >= 0);
// assert(End < Select->Tokens.Size);
New = NEW(TSelRange);
assert(New != NULL);
New->Start = Start;
New->End = End;
Rover = &Select->Ranges;
/* scan existing ranges */
while(*Rover)
/* if this one is smaller range than us */
if(((*Rover)->End - (*Rover)->Start) - 1 <= Size)
break;
else
Rover = &((*Rover)->Next);
New->Next = *Rover;
*Rover = New;
++Select->NRanges;
}
/* SelectCmpRange() - compare the maximum range of two TSelect's
*
* Sort in descending order, as we want biggest ranges first.
*/
static
int SelectCmpRange(const void* A, const void* B)
{
TSelect* a;
TSelect* b;
a = (TSelect*)A;
b = (TSelect*)B;
return -(a->NRanges - b->NRanges);
}
/* SelectCmpCount() - compare the token count of two TSelect's
*
* Sort in descending order, as we want biggest stuff first.
*/
static
int SelectCmpCount(const void* A, const void* B)
{
TSelect* a;
TSelect* b;
a = (TSelect*)A;
b = (TSelect*)B;
return -(a->Count - b->Count);
}
/* IntCmp() - sort those integers in ascending order. */
static
int IntCmp(const void* A, const void* B)
{
return ((int*)A)[0] - ((int*)B)[0];
}
/* SelectSortByRange() - sort the selection table by range.
*
* We sort by who has the biggest range (run of sequential-valued
* tokens). First, we calculate the biggest range in each TSelect,
* storing it in the MaxRange field which has lain dormant until
* now.
*/
static
void SelectSortByRange(TSelect* Table, int Size)
{
TSelect* Select;
int iSelect, iToken, Range, Start;
printf("SelectSortByRange(%d)\n", Size);
for(iSelect=0; iSelect < Size; ++iSelect)
{
Select = Table + iSelect;
/* sort tokens in ascending order */
qsort(Select->Tokens.v, Select->Tokens.Size, sizeof(int), IntCmp);
{
int i;
printf("after qsort in ascending order, token values are:\n");
for(i = 0; i < Select->Tokens.Size; ++i)
printf("%d, ", Select->Tokens.v[i]);
printf("\n");
}
Range = 1;
Start = 0;
/* start at iToken==1 because we're always looking back*/
for(iToken=1; iToken < Select->Tokens.Size; ++iToken)
{
printf("[%d/%d]=%d Range=%d [%d-%d]\n", iToken, Select->Tokens.Size,
IntGet(&Select->Tokens,iToken), Range, Start, Start+Range);
/* if this token value goes with current "range" */
if(IntGet(&Select->Tokens,iToken-1) + 1 == IntGet(&Select->Tokens,iToken))
{
/* then bump size of this range, and track max range seen */
if(++Range > Select->MaxRange)
Select->MaxRange = Range;
}
else
{
if(Range >= MINRANGE)
SelectAddRange(Select, Select->Tokens.v[Start], Select->Tokens.v[(Start+Range)-1]);
Start = iToken;
Range = 1;
}
}
if(Range >= MINRANGE)
SelectAddRange(Select, Select->Tokens.v[Start], Select->Tokens.v[(Start+Range)-1]);
printf("maximum size range was %d\n", Select->MaxRange);
}
qsort(Table, Size, sizeof(*Table), SelectCmpRange);
}
/* SelectSortByCount() - sort the selection table by count.
*
* We sort by which rule has the biggest count of associated
* tokens. Almost. Note that we have to ignore ranges of
* tokens that were already used in the code generation.
* Somebody else kindly set those token values to -1 to
* make our life easier.
*/
static
void SelectSortByCount(TSelect* Table, int Size)
{
TSelect* Select;
TSelRange* Range;
int iSelect, iTokenVal, iToken, Count;
/* first, we must remove the token ranges already used */
for(iSelect=0; iSelect < Size; ++iSelect)
{
Select = Table + iSelect;
Range = Select->Ranges;
while(Range)
{
for(iTokenVal=Range->Start; iTokenVal <= Range->End; ++iTokenVal)
{
// assert(iToken < Select->Tokens.Size);
for(iToken=0; iToken < Select->Tokens.Size; ++iToken)
if(Select->Tokens.v[iToken] == iTokenVal)
Select->Tokens.v[iToken] = -1;
}
Range = Range->Next;
}
}
for(iSelect=0; iSelect < Size; ++iSelect)
{
Select = Table + iSelect;
Count = 0;
for(iToken=0; iToken < Select->Tokens.Size; ++iToken)
{
printf("[%d]=%d ", iToken, Select->Tokens.v[iToken]);
if(Select->Tokens.v[iToken] != -1)
++Count;
}
Select->Count = Count;
printf("\n***setting count to %d\n", Select->Count);
}
qsort(Table, Size, sizeof(*Table), SelectCmpCount);
Dump("SelectSortByCount() returns\n");
}
/* TPatch - linked list for remembering back patches
*/
typedef struct TPatch
{
size_t Offset;
int RuleId;
struct TPatch* Next;
} TPatch;
static TPatch* BackPatchList;
/* MarkPatch() - remember a location for future patching.
*/
static
int MarkPatch(int IP, int RuleId)
{
TPatch* Patch = NEW(TPatch);
assert(Patch != NULL);
Patch->Offset = IP;
Patch->RuleId = RuleId;
Patch->Next = BackPatchList;
BackPatchList = Patch;
return IP + 2;
}
/* BackPatch() - backpatch some parts of the opcodes
*
* We have a linked list of offsets into Opcodes that need
* to be patched. Each patch has a rule # associated with it.
* As each rule is emitted, its actual offset into Opcodes
* becomes known. Given a rule # and an offset, we locate
* any previous calls to MarkPatch(), patch the Value into
* Opcodes, then release the patch.
*/
static
void BackPatch(TParseTables* Tables, int RuleId, int Value)
{
TPatch** Rover;
TPatch* Temp;
int Offset;
Rover = &BackPatchList;
while(*Rover)
{
Temp = *Rover;
if(Temp->RuleId == RuleId)
{
Offset = Temp->Offset;
Store16(Tables, Offset, Value);
*Rover = Temp->Next;
free(Temp);
}
else
Rover = &Temp->Next;
}
}
/* DefineTokens() - assign integer IDs to tokens as needed.
*
* The input grammar specification may include token names without
* assigning them any integer value. Here is where we assign integers
* to any such token names.
*/
static
void DefineTokens(TParseTables* Tables)
{
int NTerminals, iTerminal, InfiniteLoop;
TSymbol* Terminal;
int NextId;
Tables->MaxTokenVal = 0;
Tables->MinTokenVal = 0;
/* for each terminal */
NextId = 0;
NTerminals = SymbolListCount(Globals.Terminals);
for(iTerminal = 0; iTerminal < NTerminals; ++iTerminal)
{
Terminal = SymbolListGet(Globals.Terminals, iTerminal);
assert(Terminal != NULL);
/* want NoAction to be set to 0 anyway */
if(Terminal->Value == 0 && Terminal != NoActionSymbol)
{
for(InfiniteLoop=NextId+1024*8; SymbolFromValue(NextId) != NULL; ++NextId)
assert(NextId < InfiniteLoop); /* sanity check */
SymbolSetValue(Terminal, NextId++);
}
if(Terminal == EolSymbol)
Tables->TokenEol = EolSymbol->Value;
else if(Terminal == MatchAnySymbol)
Tables->TokenEol = MatchAnySymbol->Value;
if(Terminal->Value < Tables->MinTokenVal)
Tables->MinTokenVal = Terminal->Value;
if(Terminal->Value > Tables->MaxTokenVal)
Tables->MaxTokenVal = Terminal->Value;
}
printf("maxtok=%d mintok=%d nTerminals=%d\n",
Tables->MaxTokenVal, Tables->MinTokenVal, NTerminals);
assert((Tables->MaxTokenVal - Tables->MinTokenVal)+1 >= (NTerminals-1));
}
/* GetLLNonTerms() - get the list of LL grammar nonterminals we'll be using.
*
* For the LL(1) parser tables, a variety of nonterminals are irrelevant,
* so we just make a list of the ones that matter here.
*/
SYMBOLS GetLLNonTerms(void)
{
int NNonTerms, iNonTerm;
TSymbol* NonTerm;
SYMBOLS Result;
Result = NULL;
NNonTerms = SymbolListCount(Globals.NonTerms);
for(iNonTerm = 0; iNonTerm < NNonTerms; ++iNonTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iNonTerm);
/* if it belongs to operator precedence grammar */
if(NonTerm->OperatorTrigger)
continue; /* then skip it */
/* ignore dummy nonterminals we created for actions */
else if(SymbolIsAction(NonTerm))
continue;
/* no need to store data for implicit start symbol */
else if(NonTerm == SymbolStart())
continue;
/* otherwise, it's a nonterminal we care about! */
Result = SymbolListAdd(Result, NonTerm);
}
return Result;
}
#if 0
static
void StartRow(TParseTables* Tables)
{
/* record offset of where next variable-length row starts */
IntAdd(&Tables->LLRowStarts, Tables->LLRows.Size);
}
static
void EndRow(TParseTables* Tables)
{
/* add sentinel marker to token ID array */
IntAdd(&Tables->LLColumns, EolSymbol->Value);
/* add dummy spacer to LLRows, to keep it same size as LLColumns */
IntAdd(&Tables->LLRows, 0);
}
#endif
/* RulesEqual() - are two rules equivalent?
*
* This is a modest optimization to avoid storing space for
* two different rules that are equivalent. It is usually a
* productive optimization, simply because there will be
* multiple rules consisting of a null transition and no action.
*/
static
int RulesEqual(TRule* A, TRule* B)
{
return SymbolListEqual(A->Symbols, B->Symbols);
}
static
int AddRule(TParseTables* Tables, TRule* Rule, TSymbol* NonTerm)
{
int iRule;
/* scan list of existing unique rules */
for(iRule = 0; iRule < Tables->NRules; ++iRule)
if(RulesEqual(Tables->Rules[iRule], Rule))
{
SymbolListAddUnique(Tables->RuleSymbols[iRule], NonTerm);
break;
}
/* if this is a new unique rule */
if(iRule >= Tables->NRules)
{
int NewRuleCount = Tables->NRules+1;
Tables->Rules = realloc(Tables->Rules, NewRuleCount*sizeof(Tables->Rules[0]));
assert(Tables->Rules != NULL);
Tables->RuleSymbols = realloc(Tables->RuleSymbols, NewRuleCount*sizeof Tables->RuleSymbols[0]);
assert(Tables->RuleSymbols != NULL);
Tables->Rules[Tables->NRules] = Rule;
Tables->RuleSymbols[Tables->NRules] = SymbolListAdd(NULL, NonTerm);
Rule->RuleId = Tables->NRules;
Tables->NRules = NewRuleCount;
}
else
Rule->RuleId = Tables->Rules[iRule]->RuleId;
return Rule->RuleId;
}
/* GenerateSelect() - generate the body of the SELECT opcode.
*
* The SELECT "body" consists of data for multiple algorithms
* that associate token values with rules. The "outer" structure
* for each algorithm looks like this:
*
* +-------------+
* | entry count | 1 byte
* +-------------+
* | ... data | variable length
* +-------------+
*
* This data structure repeats (if necessary) and is terminated
* with an "entry count" of 0. Note that a particular algorithm
* may not be used for a particular SELECT body, in which case
* its very first "entry count" will be zero. IOW, it only costs
* a single null byte to skip over any algorithm deemed unproductive
* for a given SELECT body. The algorithms, in the order they
* will be expected by the interpreter, are:
*
* 1. Many tokens -> 1 rule
* +-------------+
* | token count | 1 byte
* +-------------+
* | rule | 2 bytes (rule offset)
* +-------------+
* | N tokens | variable length
* +-------------+
*
*/
static
size_t GenerateSelect(TParseTables* Tables, size_t IP, TSymbol* Symbol)
{
TSelect* SelSet;
TSelect* Select;
int SelSetSize;
TSymbol* Input;
int iSelect, iRule, iToken, NTokens, NRanges;
TRule* Rule;
SYMBOLS NextSyms;
NextSyms = Symbol->InputTokens;
/* if tail recursion, we only care about FIRST() set */
if(Symbol->Name.Text[0] == '`')
NextSyms = Symbol->First;
/* How many tokens do we have legal transitions for? */
NTokens = SymbolListCount(NextSyms);
assert(NTokens < 255);
/* remember our opcode offset; later instructions will need it */
Symbol->SelectOffset = IP - Tables->SelSectOfs;
printf("create selection set table\n");
/* create selection set table */
SelSetSize = 0;
SelSet = SelectNew(NTokens);
/* for each token this nonterminal can transition on */
for(iToken = 0; iToken < NTokens; ++iToken)
{
Input = SymbolListGet(NextSyms, iToken);
assert(Input != NULL);
/* find rule we transition to on this token */
iRule = Symbol->LLTable[iToken];
assert(iRule < RuleCount(Symbol));
assert(iRule >= 0);
Rule = Symbol->Rules[iRule];
iRule = AddRule(Tables, Rule, Symbol);
assert(Input->Value < 255);
printf("%s on %s (%d) -> %d\n", SymbolStr(Symbol), SymbolStr(Input), Input->Value, iRule);
SelSetSize = SelectAdd(SelSet, SelSetSize, iRule, Input);
}
printf("NTokens=%d, SelSetSize(# of different rules)=%d\n", NTokens, SelSetSize);
printf("sort by biggest ranges\n");
/* sort by biggest ranges */
SelectSortByRange(SelSet, SelSetSize);
/* Do the selections with sufficiently big ranges */
for(iSelect = 0; iSelect < SelSetSize; ++iSelect)
{
TSelRange* RangeRover;
Select = SelSet + iSelect;
NRanges = Select->NRanges;
printf("NRanges=%d\n", NRanges);
if(NRanges > 0)
{
IP = Store8(Tables, IP, NRanges);
IP = MarkPatch(IP, Select->Rule);
for(RangeRover=Select->Ranges; RangeRover; RangeRover=RangeRover->Next)
{
IP = Store8(Tables, IP, RangeRover->Start);
IP = Store8(Tables, IP, RangeRover->End);
}
}
else
break;
}
IP = Store8(Tables, IP, 0); /* sentinel byte */
printf("There were %d selection set ranges for '%s'\n", iSelect, SymbolStr(Symbol));
/* sort by biggest token counts per rule */
SelectSortByCount(SelSet, SelSetSize);
/* Now emit in order of largest token counts */
for(iSelect = 0; iSelect < SelSetSize; ++iSelect)
{
int TokenVal;
int Count;
Select = SelSet + iSelect;
Count = Select->Count;
printf("Count=%d\n", Count);
if(Count > 0)
{
IP = Store8(Tables, IP, Count);
IP = MarkPatch(IP, Select->Rule);
for(iToken=0; iToken < Select->Tokens.Size; ++iToken)
{
TokenVal = Select->Tokens.v[iToken];
if(TokenVal >= 0)
IP = Store8(Tables, IP, TokenVal);
}
}
}
IP = Store8(Tables, IP, 0); /* sentinel byte */
SelectDestroy(SelSet, SelSetSize);
Dump("GenerateSelect() returns IP=%d\n", IP);
return IP;
}
TParseTables* GenerateParseTables(void)
{
size_t IP, IPStart;
int NNonTerms, NSymbols;
int iRule, iTerminal;
SymIt NonTerm;
TSymbol* Symbol;
TParseTables* Tables;
SYMBOLS LLNonTerms;
int Reduced;
int TerminalsEmitted;
printf("GenerateParseTables() begins\n");
Tables = NEW(TParseTables);
assert(Tables != NULL);
Tables->LLNonTerms = LLNonTerms = GetLLNonTerms(); /* get list of only nonterminals we care about */
/* assign integers to any undefined tokens */
DefineTokens(Tables);
IP = BLC_HDR_SIZE; /* skip over initial header containing 5 two-byte table sizes */
NNonTerms = SymbolListCount(LLNonTerms);
/* generate terminal symbol table */
IPStart = IP;
TerminalsEmitted = 0;
for(iTerminal=Tables->MinTokenVal; iTerminal <= Tables->MaxTokenVal; ++iTerminal)
{
Symbol = SymbolFromValue(iTerminal);
if(Symbol)
{
/* store token ID, followed by its null-terminated string */
IP = Store8(Tables, IP, iTerminal);
IP = StoreStr(Tables, IP, SymbolStr(Symbol));
++TerminalsEmitted;
}
}
IP = Store8(Tables, IP, 0); /* sentinel byte */
Store16(Tables, BLC_HDR_TERMSYMTAB_SIZE, IP - IPStart);
/* generate nonterminal symbol table */
IPStart = IP;
NonTerm = SymItNew(LLNonTerms);
while(SymbolIterate(&NonTerm))
{
IP = StoreStr(Tables, IP, SymbolStr(NonTerm.Symbol));
}
IP = Store8(Tables, IP, 0); /* sentinel byte */
Store16(Tables, BLC_HDR_NONTERMSYMTAB_SIZE, IP - IPStart);
/* for each production of <start>, add an entry point */
IPStart = IP;
Symbol = SymbolStart();
assert(Symbol != NULL);
for(iRule = 0; iRule < RuleCount(Symbol); ++iRule)
{
/* actual value will have to be backpatched */
MarkPatch(IP, AddRule(Tables, Symbol->Rules[iRule], Symbol));
IP = Store16(Tables, IP, 0);
}
Store16(Tables, BLC_HDR_ENTRYTABLE_SIZE, IP - IPStart);
/* for each nonterminal, generate its SELECT body*/
IPStart = IP;
Tables->SelSectOfs = IPStart;
NonTerm = SymItNew(LLNonTerms);
while(SymbolIterate(&NonTerm))
IP = GenerateSelect(Tables, IP, NonTerm.Symbol);
Store16(Tables, BLC_HDR_SELECTTABLE_SIZE, IP - IPStart);
Dump("Generate opcodes for each unique rule\n");
/* generate opcodes for each unique rule */
IPStart = IP;
Tables->RuleSectOfs = IPStart;
for(iRule = 0; iRule < Tables->NRules; ++iRule)
{
int iProdItem;
TRule* Rule = Tables->Rules[iRule];
IntAdd(&Tables->RuleOffsets, IP);
Reduced = FALSE; /* have not performed a reduction for this rule yet */
NSymbols = SymbolListCount(Rule->Symbols);
fprintf(stdout, "-> ");
SymbolListDump(stdout, Rule->Symbols, " ");
fprintf(stdout, "\n");
for(iProdItem = 0; iProdItem < NSymbols; ++iProdItem)
{
TSymbol* Symbol = SymbolListGet(Rule->Symbols, iProdItem);
if(SymbolGetBit(Symbol, SYM_TERMINAL))
{
IP = Store8(Tables, IP, BLCOP_MATCH);
IP = Store8(Tables, IP, Symbol->Value);
if(Symbol == SymbolFind(EOFToken))
{
IP = Store8(Tables, IP, BLCOP_HALT);
Reduced = TRUE;
}
}
else if(SymbolIsAction(Symbol))
{
int FinalAction, ArgCount;
assert(Rule->RuleId < 255);
assert(iProdItem < 255);
FinalAction = FALSE;
if(iProdItem == NSymbols-1)
FinalAction = TRUE;
else if(Rule->TailRecursive && iProdItem == NSymbols-2)
FinalAction = TRUE;
ArgCount = iProdItem;
if(Rule->TailRecursive == 2)
++ArgCount;
fprintf(stdout, "iProdItem=%d, NSymbols=%d,TailRecursive=%d,FinalAction=%d\n", iProdItem, NSymbols, Rule->TailRecursive, FinalAction);
IP = Store8(Tables, IP, FinalAction?BLCOP_ACTRED:BLCOP_ACTION8);
IP = Store8(Tables, IP, Symbol->Action->Number);
IP = Store8(Tables, IP, ArgCount);
Symbol->Action->ArgCount = ArgCount;
if(FinalAction)
Reduced = TRUE;
}
else if(SymbolListContains(LLNonTerms, Symbol)) /* non-terminal */
{
int iSymbol = SymbolListContains(LLNonTerms, Symbol);
if(RuleCount(Symbol) > 1)
{
if(Symbol->Name.Text[0] == '`') /* if a tail recursive rule... */
{
IP = Store8(Tables, IP, BLCOP_TAILSELECT);
IP = Store8(Tables, IP, iProdItem);
Reduced = TRUE; /* TAILSELECT opcode must do the reducing to shuffle stack correctly */
}
else
IP = Store8(Tables, IP, BLCOP_LLSELECT);
IP = Store16(Tables, IP, Symbol->SelectOffset);
}
/* else, only 1 rule to choose from, so just transfer control to that rule! */
else
{
int iRule = AddRule(Tables, Symbol->Rules[0], Symbol);
IP = Store8(Tables, IP, BLCOP_CALL);
IP = MarkPatch(IP, iRule);
}
assert(iSymbol>0); /* ???TODO why is this???*/
}
else // else, it's an operator trigger
{
assert(Symbol->LR0 != NULL);
fprintf(stderr, "watch out: we don't handle LR(0) yet!\n");
}
}
if(!Reduced)
{
IP = Store8(Tables, IP, BLCOP_REDUCE);
IP = Store8(Tables, IP, NSymbols);
}
}
Store16(Tables, BLC_HDR_RULEOPCODE_SIZE, IP - IPStart);
DumpVerbose("Backpatch opcode addresses.\n");
for(iRule = 0; iRule < Tables->NRules; ++iRule)
BackPatch(Tables, iRule, Tables->RuleOffsets.v[iRule] - IPStart);
DumpVerbose("Backpatching complete.\n");
assert(IP < (1024*64));
// Opcodes = realloc(Opcodes, IP * sizeof(Opcodes[0]));
Tables->NOpcodes = IP;
Dump("GenerateParseTables() returns after %d opcodes\n", Tables->NOpcodes);
return Tables;
}
void FreeParseTables(TParseTables* Tables)
{
if(Tables)
{
if(Tables->LLNonTerms)
SymbolListDestroy(Tables->LLNonTerms);
if(Tables->Rules)
free(Tables->Rules);
if(Tables->RuleOffsets.v)
free(Tables->RuleOffsets.v);
free(Tables->Opcodes);
free(Tables);
}
}
|
100siddhartha-blacc
|
generate.c
|
C
|
mit
| 28,388
|
#ifndef OPERATOR_H_
#define OPERATOR_H_
#ifndef SYMTAB_H_
# include "symtab.h"
#endif
#ifndef PARSE_H_
# include "parse.h"
#endif
void OperatorAdd(TToken Token, int Precedence, int Associativity, SYMBOLS List, const char* Pattern);
TOperator* OperatorGet(int Which);
TOperator* OperatorFindOpSym(TOperator* Prev, TSymbol* OpSym);
int OperatorCount(void);
void OperatorCalcPrec(void);
void OperatorFree(void);
#endif /* OPERATOR_H_ */
|
100siddhartha-blacc
|
operator.h
|
C
|
mit
| 497
|
/* globals.cpp - source for Global.
*/
#include "common.h"
Global::OptionBag Global::Options =
{
-1, // ExpectCode
-1, // ExpectLine
0, // TabStop
0, // VerboseFlag
false, // TokenizeFlag
NULL, // ShowFirst
NULL, // ShowFollow
NULL, // StyleFile
};
#if 0
int Global::ExpectCode = -1;
int Global::ExpectLine = -1;
int Global::TabStop;
bool Global::DumpFlag;
bool Global::VerboseFlag;
bool Global::TokenizeFlag;
const char* Global::InputFile;
const char* Global::ShowFirst;
const char* Global::ShowFollow;
const char* Global::StyleFile;
#endif
/* ParseArgs() - parse command-line arguments.
*
*/
void Global::ParseArgs(int ArgCount, char** Args, Global::OptionBag* Temp)
{
int iArg;
const char* Arg;
if(Temp == NULL)
Temp = &Global::Options;
if(ArgCount < 2)
Usage("You must supply an input filename.\n");
for(iArg = 1; iArg < ArgCount; ++iArg)
{
Arg = Args[iArg];
if(Arg[0] == '-')
{
int Char;
++Arg;
while((Char = *Arg++) != '\0')switch(Char)
{
case 'c' :
Temp->ExpectCode = GetIntArg(Char, Arg);
Arg = Arg + strlen(Arg);
break;
case 'd' : Temp->DumpFlag = true;
break;
case 'f' :
if(Arg[-2] != '-')
Usage("'%s': -f<name> cannot be combined with other options.\n", Args[iArg]);
else
{
Temp->ShowFirst = Arg;
if(!ISALPHA(Temp->ShowFirst[0]))
Usage("Illegal character after '-f'. Use -fname to show FIRST set of non-terminal 'name'\n");
Arg += strlen(Arg);
}
break;
case 's' :
if(Arg[-2] != '-')
Usage("'%s': -s<name> cannot be combined with other options.\n", Args[iArg]);
else
{
Temp->StyleFile = Arg;
Arg += strlen(Arg);
}
break;
case 'w' :
if(Arg[-2] != '-')
Usage("'%s': -w<name> cannot be combined with other options.\n", Args[iArg]);
else
{
Temp->ShowFollow = Arg;
if(!ISALPHA(Temp->ShowFollow[0]))
Usage("Illegal character after '-w'. Use -wname to show FOLLOW set of non-terminal 'name'\n");
Arg += strlen(Arg);
}
break;
case 'k' : Temp->TokenizeFlag = true;
break;
case 'v' : ++Temp->VerboseFlag;
break;
case 'l' :
Temp->ExpectLine = GetIntArg(Char, Arg);
Arg = Arg + strlen(Arg);
break;
case 't' :
Temp->TabStop = GetIntArg(Char, Arg);
Arg = Arg + strlen(Arg);
break;
default:
Usage("'%c': Unknown option.\n", Char);
}
}
else if(Temp->InputFile == NULL)
Temp->InputFile = Arg;
else
Usage("'%s': only one input file allowed.\n", Arg);
}
if(Temp->InputFile == NULL)
Usage("Missing input file.\n");
::Dump("ParseArgs() returns\n");
}
int Global::GetIntArg(int Char, const char* Arg)
{
if(!ISDIGIT(*Arg))
ErrorExit(ERROR_COMMANDLINE, "Expecting integer after -%c.\n", Char);
return atoi(Arg);
}
|
100siddhartha-blacc
|
globals.cpp
|
C++
|
mit
| 4,284
|
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE (1024 * 2)
static
void Usage(void)
{
fprintf(stderr, "Usage:\n");
fprintf(stderr, " regress <testfile>\n");
fprintf(stderr, "Where:\n");
fprintf(stderr, " <testfile> contains directive lines.\n");
exit(EXIT_FAILURE);
}
static
int SkipLine(char* Line)
{
return *Line == '#' || strspn(Line, " \t\r\n") == strlen(Line);
}
static
int GoodLine(char* Line)
{
while(*Line)
{
if(*Line == '\n')
{
*Line++ = '\0';
return *Line == '\0';
}
++Line;
}
return 0;
}
static
int DoTest(const char* Command, int Expect, int* Result)
{
int Succeeded = 1;
printf("regress: '%s'\n", Command);
*Result = system(Command);
if(*Result == -1)
{
fprintf(stderr, "system() failed. errno=%d\n", errno);
perror("");
exit(1);
}
if(*Result != Expect)
Succeeded = 0;
return Succeeded;
}
int main(int ArgCount, const char** Args)
{
FILE* Tests;
int Expect, Got;
char* Result;
char* Command;
int LineNumber;
if(ArgCount != 2)
Usage();
Tests = fopen(Args[1], "r");
if(Tests == NULL)
{
fprintf(stderr, "Can't open '%s' for reading.\n", Args[1]);
Usage();
}
Result = malloc(MAXLINE+1);
assert(Result != NULL);
Command = malloc(MAXLINE+1);
assert(Command != NULL);
for(LineNumber=1; fgets(Command, MAXLINE, Tests); ++LineNumber)
{
if(!GoodLine(Command))
{
fprintf(stderr, "'%s' Line %d: not terminated by newline.\n", Args[1], LineNumber);
exit(EXIT_FAILURE);
}
if(SkipLine(Command))
continue;
++LineNumber;
if(fgets(Result, MAXLINE, Tests) && GoodLine(Result))
{
Expect = atoi(Result);
if(Expect < 0)
{
fprintf(stderr, "File '%s' Line %d: could not make positive integer out of '%s'\n",
Args[1], LineNumber, Result);
exit(EXIT_FAILURE);
}
if(!DoTest(Command, Expect, &Got))
{
fprintf(stderr, "File '%s' Line %d: test failed:\n '%s'\n "
"Expecting status %d, got %d\n",
Args[1], LineNumber, Command, Expect, Got);
exit(EXIT_FAILURE);
}
}
else
{
fprintf(stderr, "'%s' Line %d: not terminated by newline.\n", Args[1], LineNumber);
exit(EXIT_FAILURE);
}
}
printf("all regression tests completed successfully!\n");
return EXIT_SUCCESS;
}
|
100siddhartha-blacc
|
regress.c
|
C
|
mit
| 3,030
|
#include "common.h"
void Dump(const char* Format, ...)
{
va_list ArgPtr;
if(Global::Dump())
{
assert(Format != NULL);
va_start(ArgPtr, Format);
vfprintf(stdout, Format, ArgPtr);
va_end(ArgPtr);
fflush(stdout);
}
}
void DumpVerbose(const char* Format, ...)
{
va_list ArgPtr;
if(Global::Dump() && Global::Verbose())
{
assert(Format != NULL);
va_start(ArgPtr, Format);
vfprintf(stdout, Format, ArgPtr);
va_end(ArgPtr);
fflush(stdout);
}
}
static int ErrorCode; // connects ErrorPrologue to ErrorEpilog
/* Exit() - end-of-the-line on the way out the door.
*
* This is the final function called to exit blacc with an error.
* It handles any user option indicating that a particular error code
* and/or error on a particular line was expected, setting the exit
* status accordingly (mainly for regression tests of blacc itself).
*
* Our exit status is the (non-zero) number of the error, unless
* the user specified an expected error code/line#. In the latter
* case, the exit status is EXIT_SUCCESS if the code/line# was
* expected and EXIT_FAILURE otherwise.
**********************************************************************/
void A_NORETURN Exit(int Line, int Error)
{
int Status = -1;
/* if command-line did not request error expectations */
if(Global::Options.ExpectLine == -1 && Global::Options.ExpectCode == -1)
Status = Error;
/* else, our status is binary: were the expectations met? */
else
{
Status = EXIT_SUCCESS;
if(Global::Options.ExpectLine != -1 && Global::Options.ExpectLine != Line)
Status = EXIT_FAILURE;
else if(Global::Options.ExpectCode != -1 && Global::Options.ExpectCode != Error)
Status = EXIT_FAILURE;
}
assert(Status != -1);
fflush(stderr);
fflush(stdout);
exit(Status);
}
/* ErrorExit() - print formatted error message and exit.
*/
void A_NORETURN ErrorExit(int Code, const char* Format, ...)
{
va_list ArgPtr;
ErrorPrologue(Code);
assert(Format != NULL);
va_start(ArgPtr, Format);
vfprintf(stderr, Format, ArgPtr);
va_end(ArgPtr);
fflush(stderr);
Exit(-1, Code);
}
void ErrorPrologue(int Code)
{
fprintf(stderr, "blacc error %d:\n", Code);
fflush(stderr);
ErrorCode = Code;
}
void ErrorEpilog(int Line)
{
Exit(Line, ErrorCode);
}
/* Usage() - print formatted error, plus usage info, then exit.
*/
void Usage(const char* Format, ...)
{
va_list ArgPtr;
assert(Format != NULL);
va_start(ArgPtr, Format);
vfprintf(stderr, Format, ArgPtr);
va_end(ArgPtr);
fprintf(stderr, "Usage:\n");
fprintf(stderr, " blacc [options] file.blc\n");
fprintf(stderr, "Where:\n");
fprintf(stderr, " -c###\n");
fprintf(stderr, " causes an exit code of 1 if an error ### is not encountered.\n");
fprintf(stderr, " -d\n");
fprintf(stderr, " dumps internal information.\n");
fprintf(stderr, " -fname Display FIRST set of nonterminal 'name'.\n");
fprintf(stderr, " -k emit tokenized version of input (useless to normal users).\n");
fprintf(stderr, " -l###\n");
fprintf(stderr, " causes an exit code of 1 if an error on line ### is not found.\n");
fprintf(stderr, " -v Increase verbosity of output.\n");
fprintf(stderr, " -wname Display FOLLOW set of nonterminal 'name'.\n");
Exit(-1, ERROR_COMMANDLINE);
}
|
100siddhartha-blacc
|
common.cpp
|
C++
|
mit
| 3,785
|
#ifndef GLOBAL_H_
#define GLOBAL_H_
#endif /* GLOBAL_H_ */
|
100siddhartha-blacc
|
global.h
|
C
|
mit
| 65
|
#include "common.h"
#include "file.h"
File::File() : Buffer(nullptr), Filename(nullptr)
{
printf("Construct file!\n");
}
File::~File()
{
printf("Destruct file!\n");
if(Buffer)
free(Buffer);
}
|
100siddhartha-blacc
|
file.cpp
|
C++
|
mit
| 248
|
#nclude "walk.h"
/* for IsNullable(), we want:
* do not recurse on already visited symbol
* ignore actions
* only call me postvisit
*/
/* if we got to end of rule, rule is nullable, so This is nullable */
int IsNullableWalkEndRule(TWalk* Walk, TSymbol* This)
{
WalkResult(Walk, TRUE);
WalkPop(Walk);
}
int IsNullableWalk(TWalk* Walk, TSymbol* This)
{
int Result = FALSE;
assert(WalkWhen(Walk) == WALK_POST);
/* if it's a terminal, nothing to do (not nullable) */
if(SymbolGetBit(This, SYM_TERMINAL))
WalkNextRule(Walk);
/* else it's a non-terminal */
else
{
}
return Result;
}
|
100siddhartha-blacc
|
walk.c
|
C
|
mit
| 722
|
#include "bitset.h"
#include <limits.h>
#include <stdlib.h>
#include <assert.h>
typedef unsigned BITTYPE; /* one could tinker with different sizes... */
typedef struct TBitSet
{
int NChunks;
int NBits;
BITTYPE Bits[1];
} TBitSet;
static int BitWidth; /* how many bits wide is a BITTYPE? */
static BITTYPE* Masks; /* array of one-bit masks */
/* Init() - initialize some bitmap masks for internal use. */
static
void Init(void)
{
int iMask;
BITTYPE Mask;
BitWidth = sizeof(BITTYPE)*CHAR_BIT;
Masks = malloc(BitWidth*sizeof(BITTYPE));
assert(Masks != NULL);
/* why do it backwards? because >> is impl-defined for negatives */
Mask = 1;
for(iMask=BitWidth-1; iMask >= 0; --iMask)
{
Masks[iMask] = Mask;
Mask <<= 1;
}
}
BITSET BitSetNew(size_t Size)
{
int NChunks;
TBitSet* Result;
if(!Masks)
Init();
/* round up to nearest BITTYPE size */
NChunks = ((Size + (BitWidth-1))/BitWidth);
Result = (TBitSet*)calloc(offsetof(TBitSet,Bits) + NChunks * sizeof(BITTYPE), sizeof(char));
assert(Result != NULL);
Result->NBits = Size;
Result->NChunks = NChunks;
return (BITSET)Result;
}
void BitSetDelete(BITSET Handle)
{
free((TBitSet*)Handle);
}
BITSET BitSetOr(BITSET Handle, BITSET Other)
{
int iChunk;
TBitSet* A = (TBitSet*)Handle;
TBitSet* B = (TBitSet*)Other;
assert(A->NBits == B->NBits);
for(iChunk=0; iChunk < A->NChunks; ++iChunk)
A->Bits[iChunk] |= B->Bits[iChunk];
return Handle;
}
BITSET BitSetCopy(BITSET Handle, BITSET Other)
{
int iChunk;
TBitSet* A = (TBitSet*)Handle;
TBitSet* B = (TBitSet*)Other;
assert(A->NBits == B->NBits);
for(iChunk=0; iChunk < A->NChunks; ++iChunk)
A->Bits[iChunk] = B->Bits[iChunk];
return Handle;
}
BITSET BitSetSet(BITSET Handle, int Offset)
{
TBitSet* A = (TBitSet*)Handle;
assert(A->NBits > Offset);
A->Bits[Offset/BitWidth] |= Masks[Offset%BitWidth];
return Handle;
}
int BitSetCount(BITSET Handle)
{
int iMask, iChunk, Result=0;
TBitSet* A = (TBitSet*)Handle;
for(iChunk=0; iChunk < A->NChunks; ++iChunk)
{
BITTYPE Chunk = A->Bits[iChunk];
for(iMask=0; iMask < BitWidth; ++iMask)
if(Chunk&Masks[iMask])
++Result;
}
return Result;
}
BITITER BitIterNew(BITSET Handle)
{
BITITER Iter;
Iter.BitSet = Handle;
Iter.Index = 0;
return Iter;
}
int BitIterNext(BITITER* Iter)
{
int Result = -1; /* assume failure */
TBitSet* A = (TBitSet*)Iter->BitSet;
while(Iter->Index < A->NBits && Result == -1)
{
int iChunk = Iter->Index / BitWidth;
BITTYPE Mask = Masks[Iter->Index % BitWidth];
if(A->Bits[iChunk]&Mask)
Result = Iter->Index;
++Iter->Index;
}
return Result;
}
|
100siddhartha-blacc
|
bitset.c
|
C
|
mit
| 3,337
|
#ifndef WALK_H_
#define WALK_H_
typedef struct TWalkState
{
int iRule;
int iRhs;
TSymbol* Symbol;
int Result;
} TWalkState;
typedef struct TWalk
{
TWalkState* Stack;
int iStack;
void* UserData;
int Result;
TSymbol* Root;
} TWalk;
typedef int (*WALKER)(TWalk* Walk, TSymbol* This);
int Walk(WALKER Walker, void* Data, TSymbol* Root);
#endif
|
100siddhartha-blacc
|
walk.h
|
C
|
mit
| 500
|
#include "parse.h"
#include "compute.h"
#include "globals.h"
#include "check.h"
SYMBOLS LeftRecurSyms(TSymbol* Root, SYMBOLS Stack, SYMBOLS Checked);
/* MarkLeftRecursive() - identify left-recursive nonterminals
*
* NB: we are only marking nonterminals with simple/direct
* left recursion that we expect to later get rewritten. Other
* code will identify any more general left-recursive constructs
* that the user must rewrite.
*/
void MarkLeftRecursive(void)
{
SymIt NonTerm = SymItNew(Globals.NonTerms);
SYMBOLS List = SymbolListCreate();
Dump("MarkLeftRecursive()\n");
while(SymbolIterate(&NonTerm))
if(!SymbolIsEmpty(NonTerm.Symbol))
{
SYMBOLS Path = LeftRecurSyms(NonTerm.Symbol, NULL, NULL);
if(SymbolListCount(Path) > 0)
{
if(Globals.Dump && Globals.Verbose)
{
DumpVerbose("Left recursion path: ");
SymbolListDump(stdout, Path, " ");
DumpVerbose("\n");
}
NonTerm.Symbol->LeftRecursive = TRUE;
List = SymbolListAdd(List, NonTerm.Symbol);
}
SymbolListDestroy(Path);
}
if(SymbolListCount(List) > 0)
{
Dump("MarkLeftRecursive() found %d left-recursive non-terminals: ", SymbolListCount(List));
SymbolListDump(stdout, List, ", ");
Dump("\n");
}
else
Dump("MarkLeftRecursive() found no left-recursive non-terminals\n");
SymbolListDestroy(List);
}
/* MarkNullable() - flag all non-terminals that are nullable.
*
* For various operations, we will want to know which non-terminals
* can derive the empty string, either directly or indirectly.
* The flag TSymbol->Nullable keeps track of this, and that flag is
* set in these routines. Note that no attempt at efficiency is made.
*
* Note that the Nullable flag was set (off) for terminals when they were
* created.
*
*/
static
int IsNullable(SYMBOLS Visited, TSymbol* Symbol)
{
int Result = FALSE; /* assume not known to be nullable */
int iSymbol;
TRule** Rover;
if(SymbolGetBit(Symbol, SYM_TERMINAL) == FALSE && !SymbolListContains(Visited, Symbol))
{
SymbolListAdd(Visited, Symbol); /* add to list to avoid cycles */
Rover = Symbol->Rules;
if(Rover) for(; *Rover; ++Rover)
{
int NSymbols;
TRule* Rule = *Rover;
NSymbols = SymbolListCount(Rule->Symbols);
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
{
TSymbol* RhsSymbol = SymbolListGet(Rule->Symbols, iSymbol);
if(!IsNullable(Visited, RhsSymbol))
break;
}
if(iSymbol >= NSymbols || NSymbols == 0)
{
Result = TRUE;
break;
}
}
}
else if(SymbolGetBit(Symbol, SYM_TERMINAL))
Result = FALSE;
return Result;
}
void MarkNullable(void)
{
SYMBOLS Visited, Marked;
TSymbol* NonTerm;
int MoreFound, iNonTerm, NNonTerms;
TRule* Rule;
TRule** Rover;
Dump("MarkNullable() starts\n");
Marked = SymbolListCreate();
NNonTerms = SymbolListCount(Globals.NonTerms);
/* first, mark the directly nullable non-terminals */
for(iNonTerm=0; iNonTerm < NNonTerms; ++iNonTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iNonTerm);
Rover = NonTerm->Rules;
if(Rover) for(; (Rule=*Rover) != NULL; ++Rover)
if(SymbolListCount(Rule->Symbols) <= 0)
{
NonTerm->Nullable = TRUE;
SymbolListAdd(Marked, NonTerm);
break;
}
}
//printf("%d directly nullable\n", SymbolListCount(Marked));
//SymbolListDump(stdout, Marked, " ");
/* second, for each non-terminal, attempt to mark it nullable.
* repeat until no new non-terminals have been marked nullable
*/
do {
SymIt NonTerm = SymItNew(Globals.NonTerms);
MoreFound = FALSE;
while(SymbolIterate(&NonTerm))
if(!NonTerm.Symbol->Nullable)
{
Visited = SymbolListCreate();
if(IsNullable(Visited, NonTerm.Symbol))
{
MoreFound = TRUE;
NonTerm.Symbol->Nullable = TRUE;
}
SymbolListDestroy(Visited);
}
} while(MoreFound);
SymbolListDestroy(Marked);
if(Globals.Dump && Globals.Verbose)
{
int First = TRUE;
Dump("Nullable non-terminals:");
for(iNonTerm=0; iNonTerm < NNonTerms; ++iNonTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iNonTerm);
if(NonTerm->Nullable && !SymbolIsAction(NonTerm))
{
Dump("%s%s", First? " " : ", ", SymbolStr(NonTerm));
First = FALSE;
}
}
fprintf(stdout, "\n");
}
Dump("MarkNullable() ends\n");
}
/* MarkEmpty() - mark which non-terminals are empty (produce no symbols).
*
*/
void MarkEmpty(void)
{
SymIt NonTerm = SymItNew(Globals.NonTerms);
Dump("MarkEmpty starts\n");
DumpVerbose("Empty symbols: ");
while(SymbolIterate(&NonTerm))
{
RuleIt Rules = RuleItNew(NonTerm.Symbol);
while(RuleIterate(&Rules))
if(!SymbolIsAction(Rules.ProdItem))
break;
if(Rules.Finished)
{
DumpVerbose("%s ", SymbolStr(NonTerm.Symbol));
SymbolSetBit(NonTerm.Symbol, SYM_EMPTY);
}
}
DumpVerbose("\n");
Dump("MarkEmpty() ends\n");
}
/* AddFirst() - add FIRST(X) to existing FIRST set
*
*/
int AddFirst(SYMBOLS* ListPtr, TSymbol* ProdItem)
{
int Result = FALSE;
/* FIRST(X) is just X, if X is a terminal */
if(SymbolGetBit(ProdItem, SYM_TERMINAL))
{
if(!SymbolListContains(*ListPtr, ProdItem))
{
*ListPtr = SymbolListAdd(*ListPtr, ProdItem);
Result = TRUE;
}
}
/* otherwise, we have to add one set of symbols to another */
else if(ProdItem->First)
Result = SymbolListAddList(ListPtr, ProdItem->First);
return Result;
}
/* ClearFirstFollow() - clear the FIRST/FOLLOW sets.
*
*
*/
void ClearFirstFollow(void)
{
TRule* Rule;
TRule** Rover;
SymIt NonTerm = SymItNew(Globals.NonTerms);
while(SymbolIterate(&NonTerm))
{
SymbolListDestroy(NonTerm.Symbol->First);
SymbolListDestroy(NonTerm.Symbol->Follow);
NonTerm.Symbol->First = NULL;
NonTerm.Symbol->Follow = NULL;
NonTerm.Symbol->FirstFollowClash = FALSE;
Rover = NonTerm.Symbol->Rules;
if(Rover) for(; (Rule=*Rover) != NULL; ++Rover)
{
SymbolListDestroy(Rule->First);
Rule->First = NULL;
}
}
}
/* ComputeFirst() - compute first sets.
*
* FIRST(X) is the set of terminals that begin the strings
* you can derive from X.
*
* Note that we have to watch out for direct left recursion carefully.
* When X -> X alpha, that rule does not contribute anything to FIRST(X),
* UNLESS, X is nullable. In that case, FIRST(alpha) must be added
* to FIRST(X).
*/
void ComputeFirst(void)
{
TSymbol* NonTerm;
TSymbol* ProdItem;
TRule* Rule;
TRule** Rover;
int MoreFound, iNonTerm, NNonTerms, iProdItem, NProdItems;
NNonTerms = SymbolListCount(Globals.NonTerms);
/* do until nothing else can be added to any FIRST set */
do {
MoreFound = FALSE;
/* for each non-terminal */
for(iNonTerm = 0; iNonTerm < NNonTerms; ++iNonTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iNonTerm);
Rover = NonTerm->Rules;
if(Rover) for(; (Rule=*Rover) != NULL; ++Rover)
{
NProdItems = SymbolListCount(Rule->Symbols);
for(iProdItem = 0; iProdItem < NProdItems; ++iProdItem)
{
ProdItem = SymbolListGet(Rule->Symbols, iProdItem);
/* if it's a direct left recursive rule */
if(iProdItem == 0 && ProdItem == NonTerm)
if(NonTerm->Nullable)
continue; /* add FIRST() of rest of rule */
else
break;
if(AddFirst(&Rule->First, ProdItem))
MoreFound = TRUE;
if(AddFirst(&NonTerm->First, ProdItem))
MoreFound = TRUE;
if(ProdItem->Nullable == FALSE)
break;
}
/* if all items nullable or rule has no items */
if(iProdItem >= NProdItems || NProdItems == 0)
Rule->Nullable = TRUE;
}
}
} while(MoreFound);
}
/* AddToFollow() - add 'Follow' to FOLLOW set of 'This'.
*/
static
int AddToFollow(TSymbol* This, TSymbol* Follow, int NoClash)
{
int Result = FALSE;
if(SymbolListContains(This->First, Follow))
if(!NoClash)
{
// DumpVerbose("FIRST/FOLLOW clash for '%s' on '%s'\n", SymbolStr(This), SymbolStr(Follow));
This->FirstFollowClash = TRUE;
}
if(!SymbolListContains(This->Follow, Follow))
{
This->Follow = SymbolListAdd(This->Follow, Follow);
Result = TRUE;
}
return Result;
}
/* AddFirsts() - add FIRST(X) to FOLLOW() set, where X is a sequence of production items
*/
static
int AddFirsts(TSymbol* This, SYMBOLS Items, int iProdItem, int NoClash)
{
int Result = FALSE;
int NProdItems = SymbolListCount(Items);
/* for each item (symbol) in this production */
for(; iProdItem < NProdItems; ++iProdItem)
{
TSymbol* Item = SymbolListGet(Items, iProdItem);
SymIt First = SymItNew(Item->First);
while(SymbolIterate(&First))
if(AddToFollow(This, First.Symbol, NoClash))
Result = TRUE;
/* only proceed to next item if this one derives epsilon */
if(Item->Nullable == FALSE)
break;
}
return Result;
}
/* StrIsNullable() - is a string (list) of symbols nullable?
*/
static
int StrIsNullable(SYMBOLS List, int iSymbol)
{
int Result = TRUE;
int NSymbols = SymbolListCount(List);
for(; iSymbol < NSymbols; ++iSymbol)
{
TSymbol* Symbol = SymbolListGet(List, iSymbol);
if(!Symbol->Nullable)
{
Result = FALSE;
break;
}
}
return Result;
}
/* ComputeFollow() - compute the FOLLOW() set of all non-terminals.
*
* This is standard LL(1) algorithm stuff, except for the complication
* of our inclusion of operator precedence functionality. If a non-terminal
* A is an "operator trigger", then we ignore the productions of A when
* computing FOLLOW(A).
*/
void ComputeFollow(void)
{
TSymbol* NonTerm;
TSymbol* ProdItem;
TSymbol* Start;
TRule* Rule;
TRule** Rover;
int MoreFound, iNonTerm, NNonTerms, iProdItem, NProdItems;
int iLoop, MaxLoop;
Start = SymbolStart();
assert(Start != NULL);
/* put '$' in FOLLOW() set of start symbol */
Start->Follow = SymbolListAdd(Start->Follow, EndSymbol);
NNonTerms = SymbolListCount(Globals.NonTerms);
iLoop = 0;
MaxLoop = NNonTerms * NNonTerms;
/* do until nothing can be added to any FOLLOW set */
do {
MoreFound = FALSE;
++iLoop;
assert(iLoop <= MaxLoop); /* defense against infinite loop */
/* for each nonterminal */
for(iNonTerm = 0; iNonTerm < NNonTerms; ++iNonTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iNonTerm);
if(NonTerm->OperatorTrigger)
continue;
/* for each rule in this nonterminal */
Rover = NonTerm->Rules;
if(Rover) for(; (Rule = *Rover) != NULL; ++Rover)
{
int DLR = FALSE;
NProdItems = SymbolListCount(Rule->Symbols);
/* if nonterm is nullable and rule is Direct Left Recursion */
// if(NonTerm->Nullable && NProdItems > 1 && SymbolListGet(Rule->Symbols, 0) == NonTerm)
if(NonTerm->Nullable && NProdItems > 1 && SymbolListGet(Rule->Symbols, 0) == NonTerm)
DLR = TRUE;
/* for each item in this rule */
for(iProdItem = 0; iProdItem < NProdItems; ++iProdItem)
{
ProdItem = SymbolListGet(Rule->Symbols, iProdItem);
if(SymbolGetBit(ProdItem, SYM_TERMINAL) == FALSE)
{
/* if it's not the last item in the rule */
if(iProdItem < (NProdItems-1))
/* if X is the list of symbols to right, add FIRST(X) to FOLLOW(this) */
if(AddFirsts(ProdItem, Rule->Symbols, iProdItem+1, (iProdItem==0) && DLR))
MoreFound = TRUE;
/* if it is the last item, or items to right are nullable */
if(iProdItem == (NProdItems-1) || StrIsNullable(Rule->Symbols, iProdItem+1))
{
SymIt Follow = SymItNew(NonTerm->Follow);
while(SymbolIterate(&Follow))
if(AddToFollow(ProdItem, Follow.Symbol, FALSE))
MoreFound = TRUE;
}
// if(SymbolListAddList(&ProdItem->Follow, NonTerm->Follow))
// MoreFound = TRUE;
}
}
}
}
} while(MoreFound);
}
/* ComputeEndsWith() - compute ends-with relation for all nonterminals
*
* ENDSWITH(X) is the set of all nonterminals that can appear at the
* end of a string derived from X.
*
* Note that we do not automatically include X in ENDSWITH(X). If
* X appears in ENDSWITH(X), that means X is right-recursive.
*/
void ComputeEndsWith()
{
int iQueue, iProdItem;
TRule* Rule;
TRule** Rover;
SYMBOLS Queue;
TSymbol* Trailing;
TSymbol* This;
SymIt NonTerm = SymItNew(Globals.NonTerms);
if(Globals.Dump) printf("ComputeEndsWith()\n");
while(SymbolIterate(&NonTerm))
{
This = NonTerm.Symbol;
iQueue = -1;
Queue = NULL;
do {
Rover = This->Rules;
if(Rover) for(; (Rule=*Rover) != NULL; ++Rover)
{
/* scan symbols in this production, backward from the right */
iProdItem = SymbolListCount(Rule->Symbols);
while(--iProdItem >= 0)
{
assert(Rule->Symbols != NULL);
Trailing = SymbolListGet(Rule->Symbols, iProdItem);
assert(Trailing != NULL);
if(SymbolGetBit(Trailing, SYM_TERMINAL) == FALSE)
Queue = SymbolListAddUnique(Queue, Trailing);
if(!Trailing->Nullable)
break;
}
}
} while((This=SymbolListGet(Queue, ++iQueue)) != NULL);
#if 0
printf("ENDSWITH(%s) = ", SymbolStr(NonTerm.Symbol));
SymbolListDump(stdout, Queue, ", ");
printf("\n");
#endif
NonTerm.Symbol->EndsWith = Queue;
}
}
/* ??? need detailed design of how conflicts are resolved.
* ??? need ability to show detailed list of conflicts when dumping LL table.
*/
static
int LLConflict(TSymbol* NonTerm, TSymbol* Terminal, int Existing, int New)
{
int RuleToStore = New;
TRule* OldRule;
TRule* NewRule;
TRule* Stored = NULL;
OldRule = NonTerm->Rules[Existing];
NewRule = NonTerm->Rules[New];
if(NonTerm->Name.Text[0] == '`') /* if this is a left-recursive rewrite symbol */
{
if(OldRule->Nullable && !NewRule->Nullable)
{
RuleToStore = New;
Stored = NewRule;
}
else if(NewRule->Nullable && !OldRule->Nullable)
{
RuleToStore = Existing;
Stored = OldRule;
}
}
else
{
fprintf(stderr, "Nonterminal '%s': conflict on token %s\n",
SymbolStr(NonTerm), SymbolStr(Terminal));
fprintf(stderr, "Can't choose between the following two productions:\n");
fprintf(stderr, " (rule %d)-> ", Existing);
SymbolListDump(stderr, NonTerm->Rules[Existing]->Symbols, " ");
fprintf(stderr, "\n");
fprintf(stderr, " (rule %d)-> ", New);
SymbolListDump(stderr, NonTerm->Rules[New]->Symbols, " ");
fprintf(stderr, "\n");
//??? return 1;
}
#if 0
printf("%.*s(%.*s) reject epsilon for: ",
NonTerm->Name.TextLen, NonTerm->Name.Text,
Terminal->Name.TextLen, Terminal->Name.Text);
assert(Stored != NULL);
SymbolListDump(stdout, Stored->Symbols, " ");
printf("\n");
#endif
/* if we're going to clobber an existing rule */
if(RuleToStore != Existing)
{
int iRule;
for(iRule = 0; iRule < SymbolListCount(NonTerm->InputTokens); ++iRule)
{
if(NonTerm->LLTable[iRule] == Existing)
{
NonTerm->LLTable[iRule] = RuleToStore;
break;
}
}
assert(iRule < SymbolListCount(NonTerm->InputTokens));
}
return 0;
}
/* AddLLTableRule() - Define rule to expand when non-terminal encounters given token.
*/
static
int AddLLTableRule(TSymbol* NonTerm, TSymbol* InputToken, int iRule)
{
int NTokens;
int ExistingRule;
int Conflict = 0;
int OkToAddRule = FALSE;
ExistingRule = SymbolListContains(NonTerm->InputTokens, InputToken)-1;
/* if we got a problem because grammar ain't LL(1) */
if(ExistingRule >= 0)
{
ExistingRule = NonTerm->LLTable[ExistingRule];
LLConflict(NonTerm, InputToken, ExistingRule, iRule);
// OkToAddRule = TRUE;
// ++Conflict;
}
else
OkToAddRule = TRUE;
if(OkToAddRule)
{
NonTerm->InputTokens = SymbolListAdd(NonTerm->InputTokens, InputToken);
NTokens = SymbolListCount(NonTerm->InputTokens);
NonTerm->LLTable = (int*)realloc(NonTerm->LLTable, NTokens*sizeof(int));
assert(NonTerm->LLTable != NULL);
NonTerm->LLTable[NTokens-1] = iRule;
}
return Conflict;
}
/* ComputeLLTable() - try to construct an LL parsing table.
*
* The "table" is actually distributed across the non-terminals in the
* symbol table. Each non-terminal contains two parallel arrays. InputTokens
* is an array of the input tokens that are legal when that non-terminal is
* on top of the parsing stack. LLTable is a parallel array of integers, where
* each integer identifies the rule of that non-terminal associated with
* the corresponding input token.
*/
void ComputeLLTable(void)
{
int NNonTerms, iTerm, iRule;
TSymbol* NonTerm;
TSymbol* InputToken;
TSymbol* Start;
int ErrorCount = 0;
Start = SymbolStart();
/* for each non-terminal */
NNonTerms = SymbolListCount(Globals.NonTerms);
for(iTerm = 0; iTerm < NNonTerms; ++iTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iTerm);
assert(RuleCount(NonTerm) > 0); /* sanity check */
/* if it belongs to operator precedence grammar or is implicit start symbol */
if(NonTerm->OperatorTrigger || NonTerm == Start)
continue; /* then skip it */
/* for each rule (aka production) of this non-terminal */
for(iRule = 0; iRule < RuleCount(NonTerm); ++iRule)
{
int NFirst, iFirst;
TRule* Rule = NonTerm->Rules[iRule];
/* for each symbol in the FIRST set of this rhs */
NFirst = SymbolListCount(Rule->First);
for(iFirst = 0; iFirst < NFirst; ++iFirst)
{
InputToken = SymbolListGet(Rule->First, iFirst);
if(SymbolGetBit(InputToken, SYM_TERMINAL))
ErrorCount += AddLLTableRule(NonTerm, InputToken, iRule);
}
/* if FIRST(rhs) contains epsilon */
if(Rule->Nullable)
{
int NFollow, iFollow;
/* handle terminals in FOLLOW set of non-terminal */
NFollow = SymbolListCount(NonTerm->Follow);
for(iFollow = 0; iFollow < NFollow; ++iFollow)
{
InputToken = SymbolListGet(NonTerm->Follow, iFollow);
if(SymbolListContains(Rule->First, InputToken))
{
/*???TODO???*/
fprintf(stderr, "Can't happen: nonterm '%s', rule '%d' first/follow clash on %s\n",
SymbolStr(NonTerm), iRule, SymbolStr(InputToken));
}
if(SymbolGetBit(InputToken, SYM_TERMINAL))
AddLLTableRule(NonTerm, InputToken, iRule);
}
}
}
}
if(ErrorCount)
Exit(-1, ERROR_LL_CONFLICT);
}
#if 0
void ComputeOperators(void)
{
int NNonTerms, iTerm, iRule;
TSymbol* NonTerm;
TSymbol* InputToken;
NNonTerms = SymbolListCount(Globals.NonTerms);
for(iTerm = 0; iTerm < NNonTerms; ++iTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iTerm);
/* if it's not an operator grammar start symbol */
if(!NonTerm->OperatorTrigger)
continue; /* then skip it */
fprintf(stderr, "THis code ain't writ yet!\n\n\n--\n");
/* for each rule of the operator trigger */
for(iRule = 0; iRule < NonTerm->NRules; ++iRule)
{
int NFirst, iFirst;
TRule* Rule = NonTerm->Rules[iRule];
NFirst = SymbolListCount(Rule->First);
for(iFirst = 0; iFirst < NFirst; ++iFirst)
{
InputToken = SymbolListGet(Rule->First, iFirst);
if(SymbolGetBit(InputToken, SYM_TERMINAL))
AddLLTableRule(NonTerm, InputToken, iRule);
}
if(Rule->Nullable)
{
int NFollow, iFollow;
NFollow = SymbolListCount(NonTerm->Follow);
for(iFollow = 0; iFollow < NFollow; ++iFollow)
{
InputToken = SymbolListGet(NonTerm->Follow, iFollow);
if(SymbolGetBit(InputToken, SYM_TERMINAL))
AddLLTableRule(NonTerm, InputToken, iRule);
}
}
}
}
}
#endif
/*************************************************************
* Computing operator precedence table
*************************************************************/
void ComputePrecTable(void)
{
}
/* LeftRecurSyms() - Locate symbols involved in left recursion, if any.
*
* This = top of Stack
*
* for each proditem of each rule
* if(proditem is action)
* continue
* else if(proditem is terminal)
* break
* if(proditem == Root)
* add Stack to Found
* continue
* if(proditem not in Checked)
* push proditem on Stack
* add LeftRecurSyms() to Found
* if(proditem not nullable)
* break
*
* pop Stack
* return Found
*/
SYMBOLS LeftRecurSyms(TSymbol* Root, SYMBOLS Stack, SYMBOLS Checked)
{
TSymbol* This;
RuleIt Rules;
SYMBOLS Found = NULL;
DumpVerbose("LeftRecurSyms('%s', %d, %d)\n", SymbolStr(Root), SymbolListCount(Stack), SymbolListCount(Checked));
/* initialization for first invocation */
if(Stack == NULL)
{
assert(Checked == NULL);
Stack = SymbolListAdd(NULL, Root);
Checked = SymbolListCreate();
}
This = SymbolListTop(Stack);
if(SymbolListContains(Checked, This) || SymbolIsEmpty(This))
{
DumpVerbose("LeftRecurSyms('%s', %d, %d) skips %s\n", SymbolStr(Root), SymbolListCount(Stack), SymbolListCount(Checked), SymbolStr(This));
return NULL;
}
else
Checked = SymbolListAdd(Checked, This);
/* for every production item in every rule */
for(Rules = RuleItNew(This); RuleIterate(&Rules); )
if(SymbolGetBit(Rules.ProdItem, SYM_TERMINAL))
RuleItNext(&Rules); /* go to next rule; this rule can't lead to left recursion */
else
{
if(Rules.ProdItem == Root)
SymbolListAddList(&Found, Stack);
else
{
Stack = SymbolListPush(Stack, Rules.ProdItem);
SymbolListAddList(&Found, LeftRecurSyms(Root, Stack, Checked));
}
}
SymbolListPop(Stack);
DumpVerbose("LeftRecurSyms('%s', %d, %d) returns %d\n", SymbolStr(Root), SymbolListCount(Stack), SymbolListCount(Checked), SymbolListCount(Found));
if(SymbolListCount(Stack) == 0)
{
SymbolListDestroy(Checked);
SymbolListDestroy(Stack);
}
return Found;
}
/* GenerateComboNonTerm() - create a nonterminal from two other symbol names.
*
* This is used in the left corner transformation algorithm.
*/
static
TSymbol* GenerateComboNonTerm(TSymbol* A, TSymbol* B)
{
TSymbol* Combo;
TToken Token;
Token = TokenFake(TK_IDENT, "[%s-%s]", SymbolStr(A), SymbolStr(B));
Combo = SymbolFind(Token);
if(!Combo)
Combo = SymbolNewNonTerm(Token);
return Combo;
}
/* GenerateUniqueNonTerm() - create a new nonterminal with a unique name.
*/
static
TSymbol* GenerateUniqueNonTerm(TSymbol* NonTerm, char C)
{
int Collision;
TSymbol* Unique;
TToken Token;
char Buffer[128];
//printf(". GenerateUniqueNonTerm(%s) = ", SymbolStr(NonTerm));
for(Collision=0; ; ++Collision)
{
int iChar;
for(iChar = 0; iChar <= Collision; ++iChar)
Buffer[iChar] = C;
Buffer[iChar] = '\0';
Token = TokenFake(TK_IDENT, "%s%.*s",
Buffer, NonTerm->Name.TextLen, NonTerm->Name.Text);
if(!SymbolFind(Token))
{
//printf(" '%.*s'\n", Token.TextLen, Token.Text);
Unique = SymbolNewNonTerm(Token);
break;
}
assert(Collision < 127);
}
return Unique;
}
#if 0
/* RemoveLeftRecursion() - rewrite a nonterminal to remove left recursion.
*
* The caller has identified for us which rules are left recursive and which
* are not. Suppose the original nonterminal looks like this:
*
* A : A x
* | x
* ;
*
* Then our rewritten grammar would be:
*
* `A : x `A
* | ;
* A : x `A
* ;
*/
static
void RemoveLeftRecursion(TSymbol* NonTerm, TRule**Left, int NLeft)
{
int iRule, jRule;
TSymbol* NewNonTerm;
fprintf(stdout, ">>>>>>>remove %d left-recursive rules from '%.*s'\n",
NLeft,
NonTerm->Name.TextLen, NonTerm->Name.Text);
DumpTreeSymbol(NonTerm, FALSE);
/* create new non-terminal to hold recursive tails */
NewNonTerm = GenerateUniqueNonTerm(NonTerm, '`');
/* now modify the rules of the original nonterminal */
for(iRule = jRule = 0; iRule < NonTerm->NRules; ++iRule)
{
TRule* Rule = NonTerm->Rules[iRule];
if(IsLeftRecursive(Rule, NonTerm))
continue;
/* else, this rule is not left-recursive, but must be modified */
else
{
/* copy into its new position */
NonTerm->Rules[jRule] = Rule;
/* and make it end new, synthesized nonterminal */
Rule->Symbols = SymbolListAdd(Rule->Symbols, NewNonTerm);
++jRule;
Rule->TailRecursive = 1;
}
}
assert(jRule == NonTerm->NRules - NLeft);
NonTerm->NRules = jRule; /* correct the count of rules */
/* give the new nonterminal all the left-recursive rules */
NewNonTerm->NRules = NLeft;
NewNonTerm->Rules = Left;
/* but make them right-recursive */
for(iRule = 0; iRule < NLeft; ++iRule)
{
TSymbol* Dummy;
TRule* Rule = Left[iRule];
Dummy = SymbolListDelete(Rule->Symbols, 0);
assert(Dummy == NonTerm);
Rule->Symbols = SymbolListAdd(Rule->Symbols, NewNonTerm);
Rule->TailRecursive = 2;
}
/* and add empty production */
SymbolNewRule(NewNonTerm);
/* and mark it nullable! (we're not calling MarkNullable() a 2nd time)*/
NewNonTerm->Nullable = TRUE;
DumpTreeSymbol(NonTerm, FALSE);
DumpTreeSymbol(NewNonTerm, FALSE);
}
#else
/* AddLeftCorners() - add left corners of NonTerm to symbol list.
*
* By left corners, we mean the transitive closure of
* the direct left corner relationship.
*
*/
SYMBOLS AddLeftCorners(SYMBOLS LeftCorners, TSymbol* NonTerm)
{
int iSymbol, NProdItems, iProdItem;
TSymbol* Symbol;
TRule** Rover;
TRule* Rule;
LeftCorners = SymbolListAddUnique(LeftCorners, NonTerm);
for(iSymbol = 0; iSymbol < SymbolListCount(LeftCorners); ++iSymbol)
{
Symbol = SymbolListGet(LeftCorners, iSymbol);
/* For each rule of this non-terminal */
Rover = Symbol->Rules;
if(Rover) for(; (Rule=*Rover) != NULL; ++Rover)
{
NProdItems = SymbolListCount(Rule->Symbols);
for(iProdItem = 0; iProdItem < NProdItems; ++iProdItem)
{
TSymbol* ProdItem;
ProdItem = SymbolListGet(Rule->Symbols, iProdItem);
LeftCorners = SymbolListAddUnique(LeftCorners, ProdItem);
break;
if(SymbolIsAction(ProdItem))
continue;
if(!ProdItem->Nullable)
break;
}
}
}
if(Globals.Dump && Globals.Verbose)
{
DumpVerbose("LeftCorner('%s')=", SymbolStr(NonTerm));
SymbolListDump(stdout, LeftCorners, ", ");
DumpVerbose("\n");
}
return LeftCorners;
}
/* LCXFormTerminal() - create left-corner transformation rule for a terminal.
*
* Original non-terminal had a terminal ("a") in its left corner,
* so we create this:
* A -> a A-a
*/
static TRule* LCXFormTerminal(SYMBOLS SubGrammar, TSymbol* NonTerm, TSymbol* Terminal)
{
TRule* NewRule = SymbolNewRule(NonTerm);
TSymbol* Synth = GenerateComboNonTerm(NonTerm, Terminal);
DumpVerbose("'%s' had terminal '%s' in its left corner, so create %s : %s [%s-%s]\n",
SymbolStr(NonTerm), SymbolStr(Terminal), SymbolStr(NonTerm), SymbolStr(Terminal), SymbolStr(NonTerm), SymbolStr(Terminal));
RuleAddSymbol(NewRule, Terminal, Terminal->Name);
RuleAddSymbol(NewRule, Synth, Synth->Name);
SubGrammar = SymbolListAddUnique(SubGrammar, Synth);
return NewRule;
}
/* LCXFormNullable() - create left-corner transformation rule for nullable non-terminal
*
* Original non-terminal had a non-terminal ("C") containing an epsilon production
* in its left corner, so we create this:
* A -> A-C
* Note that it doesn't matter if "C" happens to be "A".
*/
static TRule* LCXFormNullable(SYMBOLS SubGrammar, TSymbol* A, TSymbol* C)
{
TRule* NewRule = SymbolNewRule(A);
TSymbol* Synth = GenerateComboNonTerm(A, C);
DumpVerbose("'%s' had epsilon-producing '%s' in its left corner, so create %s : [%s-%s]\n",
SymbolStr(A), SymbolStr(C), SymbolStr(A), SymbolStr(A), SymbolStr(C));
RuleAddSymbol(NewRule, Synth, Synth->Name);
SubGrammar = SymbolListAddUnique(SubGrammar, Synth);
SubGrammar = SymbolListAddUnique(SubGrammar, C);
return NewRule;
}
/* LCXFormRule() - create left-corner transformation of rule.
*
* While processing non-terminal A, We found a production like this:
* B -> X beta
* and must transform it to this:
* A-X -> beta A-B
* Additionally, if this rule is from our root symbol, we need
* A-X -> beta
* However, that is really the special case of tail recursion that
* we want to optimize out. Therefore, in that case, we emit a single
* single transformed production rather than two:
* A-A -> beta {} A-A
*
*/
static void LCXFormRule(SYMBOLS SubGrammar, TSymbol* A, TSymbol* B, TRule* OldRule)
{
TSymbol* X;
TSymbol* AminusB;
TSymbol* AminusX;
TRule* NewRule;
Dump("LCXFormRule(A=%s,B=%s)\n", SymbolStr(A), SymbolStr(B));
/* create and remember new non-terminal named "A-B" */
AminusB = GenerateComboNonTerm(A, B);
SubGrammar = SymbolListAddUnique(SubGrammar, AminusB);
NewRule = RuleDup(OldRule);
#if 0
while((X=RuleRemoveSymbol(NewRule, 0)) != NULL)
if(!SymbolIsAction(X))
break;
#else
X = RuleRemoveSymbol(NewRule, 0);
#endif
assert(X != NULL);
Dump(" removed X = '%s'\n", SymbolStr(X));
/* create and remember new non-terminal named "A-X" */
AminusX = GenerateComboNonTerm(A, X);
SubGrammar = SymbolListAddUnique(SubGrammar, AminusX);
if(A == B)
{
// ??? add marker non-term for left recursion
RuleAddSymbol(NewRule, SymbolFind(ReduceToken), ReduceToken);
RuleAddSymbol(NewRule, AminusB, AminusB->Name);
}
else
{
RuleAddSymbol(NewRule, AminusB, AminusB->Name);
}
SymbolAddRule(AminusX, NewRule);
Dump("LCXFormRule() returns\n");
}
/* RemoveLeftRecursion() - rewrite a nonterminal to remove left recursion.
*
* TODO: this code is not right. Could be multiple left recursions that share
* a common "innocent" rule(s).
*
* Use a left-corner transformation to rewrite this non-terminal
* (and possibly others) to remove left recursion (note that
* new rules with common left factors may be introduced).
*
*/
static void RemoveLeftRecursion(TSymbol* Root)
{
SYMBOLS SubGrammar = NULL;
SYMBOLS LeftCorners = NULL;
SymIt Corner;
TRule* OldRule;
TRule** Rover;
if(Globals.Dump && Globals.Verbose)
{
DumpVerbose(">>>>>>>remove left-recursion starting at '%s'\n", SymbolStr(Root));
DumpTreeSymbol(Root, FALSE);
}
/* find the left corners of this root */
LeftCorners = AddLeftCorners(LeftCorners, Root);
assert(SymbolListContains(LeftCorners, Root));
/* keep track of all non-terminals in transformed sub-grammar */
SubGrammar = SymbolListAdd(NULL, Root);
/* wipe out rules, but first save in a safe spot */
Root->OrigRules = Root->Rules;
Root->Rules = NULL;
/* for each symbol that is in "full" left corner of Root */
Corner = SymItNew(LeftCorners);
while(SymbolIterate(&Corner))
{
DumpVerbose("Processing left corner '%s'\n", SymbolStr(Corner.Symbol));
/* if it's a terminal */
if(SymbolGetBit(Corner.Symbol, SYM_TERMINAL))
LCXFormTerminal(SubGrammar, Root, Corner.Symbol);
else if(SymbolIsAction(Corner.Symbol))
LCXFormTerminal(SubGrammar, Root, Corner.Symbol);
/* else it's a non-terminal */
else
{
SubGrammar = SymbolListAddUnique(SubGrammar, Corner.Symbol);
Rover = Corner.Symbol->OrigRules ? Corner.Symbol->OrigRules : Corner.Symbol->Rules;
assert(Rover != NULL);
assert(*Rover != NULL); /* sanity check: must have at least one rule! */
/* for each rule in this non-terminal */
for(; *Rover; ++Rover)
{
OldRule = *Rover;
#if 0
if(RuleItemCount(OldRule) == 0)
LCXFormNullable(SubGrammar, Root, Corner.Symbol);
if(RuleItemCount(OldRule) == 0)
{
/* if root has epsilon production, must copy it verbatim */
if(Corner.Symbol == Root)
SymbolDupRule(Root, OldRule);
}
/* else rule has at least one symbol */
else
#endif
LCXFormRule(SubGrammar, Root, Corner.Symbol, OldRule);
}
}
}
if(Globals.Dump && Globals.Verbose)
{
SymIt NonTerms;
DumpVerbose("Rewritten '%s' is: \n", SymbolStr(Root));
NonTerms = SymItNew(SubGrammar);
while(SymbolIterate(&NonTerms))
DumpTreeSymbol(NonTerms.Symbol, FALSE);
}
SymbolListDestroy(LeftCorners);
DumpVerbose("<<<<<<<\n");
}
#endif
/* CommonRhs() - report length of right-hand-side common prefix in two rules.
*
* This function determines whether two rules are candidates for
* left factoring. However, it also performs three important error
* checks.
*
* First, it is an error if two rules have right-hand-sides
* with identical sequences of symbols (modulo actions).
*
* Second, it is an error if two rules have prefixes that
* differ only because of embedded actions.
*
* Third, it is an error if two rules with common prefixes
* have suffixes that cannot be distinguished.
*/
static
int FindShortestPrefix(TSymbol* NonTerm)
{
int Shortest = 0;
TRule** Rules = NonTerm->Rules;
int NRules = RuleCount(NonTerm);
int iRule;
/* scan all the rules */
for(iRule = 0; iRule < NRules; ++iRule)
{
TRule* Rule = Rules[iRule];
/* if this rule has a prefix in common with another rule */
if(Rule->LeftFactor > 0)
{
if(Shortest == 0 || Rule->LeftFactor < Shortest)
Shortest = Rule->LeftFactor;
if(Shortest == 1) /* can't get any shorter than that! */
break;
}
}
//fprintf(stderr, "FindShortestPrefix returns %d\n", Shortest);
return Shortest;
}
/* NumberCommonLeft() - assign common left factor length to each rule.
*
* Assign each rule a number equal to the length of the largest
* prefix it has in common with other rules from this nonterminal.
* Ignore nonterminals that are placeholders for actions at this stage.
*/
static
void NumberCommonLeft(TSymbol* NonTerm)
{
TRule** Rules;
int NRules;
int iRule;
int HighScore = 0;
NRules = RuleCount(NonTerm);
Rules = NonTerm->Rules;
/* initialize length of longest common left factor to zero
*/
for(iRule = 0; iRule < NRules; ++iRule)
Rules[iRule]->LeftFactor = 0;
for(iRule = 0; iRule < (NRules-1); ++iRule)
{
int jRule, Score;
TRule* RuleA = Rules[iRule];
/* compare each rule to those after it */
for(jRule = iRule+1; jRule < NRules; ++jRule)
{
TRule* RuleB = Rules[jRule];
Score = CommonLeft(NonTerm, RuleA->Symbols, RuleB->Symbols);
if(Score > RuleA->LeftFactor)
RuleA->LeftFactor = Score;
if(Score > RuleB->LeftFactor)
RuleB->LeftFactor = Score;
if(Score > HighScore)
HighScore = Score;
}
}
if(Globals.Dump && HighScore)
printf(" '%.*s' has one or more rules with common left prefixes of length %d.\n",
NonTerm->Name.TextLen, NonTerm->Name.Text, HighScore);
}
/* RuleMoveSuffix() - use suffix from one rule to make a new rule.
*
* Called during left factoring to clip the suffix from
* a rule and use it to make a new rule in another nonterminal.
*/
static
void RuleMoveSuffix(TRule* Rule, int PrefixLen, TSymbol* NewNonTerm)
{
int iSymbol, nSymbols, Len;
TRule* NewRule;
//fprintf(stderr, "RuleMoveSuffix(PrefixLen=%d)\n", PrefixLen);
/* create empty rule in target nonterminal */
NewRule = SymbolNewRule(NewNonTerm);
/* locate first symbol of suffix */
nSymbols = SymbolListCount(Rule->Symbols);
//fprintf(stderr, ". RuleMoveSuffix(PrefixLen=%d) nSymbols=%d\n", PrefixLen, nSymbols);
for(Len = iSymbol = 0; iSymbol < nSymbols; ++iSymbol)
{
TSymbol* Symbol = SymbolListGet(Rule->Symbols, iSymbol);
if(!SymbolIsAction(Symbol))
if(++Len >= PrefixLen)
break;
}
//fprintf(stderr, ". prefix is %d symbols\n", iSymbol+1);
/* move any remaining symbols over */
for(++iSymbol; iSymbol < nSymbols; ++iSymbol)
{
TSymbol* Symbol = SymbolListGet(Rule->Symbols, iSymbol);
RuleAddSymbol(NewRule, Symbol, Rule->Tokens[iSymbol]);
}
//fprintf(stderr, ". New length is %d symbols\n", SymbolListCount(Rule->Symbols));
NewRule->RuleId = Rule->RuleId;
//fprintf(stderr, ". new rule: %s -> ", SymbolStr(NewNonTerm));
//SymbolListDump(stderr, NewRule->Symbols, " ");
//fprintf(stderr, "\n");
}
static
void RuleRemove(TSymbol* NonTerm, int iRemove)
{
TRule** Rules = NonTerm->Rules;
TRule* Rule;
int NRules = RuleCount(NonTerm);
int iRule;
assert(iRemove < NRules);
assert(iRemove >= 0);
Rule = Rules[iRemove];
RuleFree(Rule);
/* shift all the other rules down */
for(iRule = iRemove; iRule+1 < NRules; ++iRule)
{
Rules[iRule] = Rules[iRule+1];
}
Rules[iRule] = NULL;
}
static
void RuleTruncate(TRule* Rule, int PrefixLen)
{
int iSymbol, nSymbols, Len;
/* locate first symbol of suffix */
nSymbols = SymbolListCount(Rule->Symbols);
for(Len = iSymbol = 0; iSymbol < nSymbols; ++iSymbol)
{
TSymbol* Symbol = SymbolListGet(Rule->Symbols, iSymbol);
if(!SymbolIsAction(Symbol))
if(++Len >= PrefixLen)
break;
}
SymbolListTruncate(Rule->Symbols, iSymbol+1);
}
/* RewriteCommonLeft() - the basic unit of left-factoring.
*
* The caller knows that NonTerm contains two or more rules
* with a common left factor of Length symbols. This function
* locates the first such rule, then factors out that rule
* and the one or more other rules that share the left factor
* of that length. Example:
*
* A : A B C D | A B C E
*
* becomes
*
* A : A B C `A
* `A : D | E
*
* Note that Length alone does not uniquely identify a
* group of rules with a common left factor:
*
* A
* : A B C D
* | A B C E
* | X Y Z D
* | X Y Z E
* ;
*
* The preceding grammar fragment contains two separate
* groups of rules with common left factors of length 3.
* That's OK; this function just rewrites the first group
* of a given length that it runs into. The caller will
* call us again with the same Length if necessary.
*
* Note also that common left factoring may leave more
* factoring work to do:
*
* A : A B C D | A B C E | A B F
*
* becomes
*
* A : A B #A
* #A : C D | C E | F
*
* And the revised version of nonterminal A still has
* a common left factor. That's OK too; we keep removing
* common left factors in a loop until none are left.
*/
static
void RewriteCommonLeft(TSymbol* NonTerm, int Length)
{
int iRule, OrigRuleCount, iTarget;
TRule** Rules;
TRule* Rule;
TSymbol* NewNonTerm;
//printf(".RewriteCommonLeft('%s')\n", SymbolStr(NonTerm));
//fprintf(stderr, ". Before left factoring, rule count = %d\n", NonTerm->NRules);
/* locate first rule with common left factor of this length */
Rules = NonTerm->Rules;
OrigRuleCount = RuleCount(NonTerm);
Rule = NULL;
for(iTarget = 0; iTarget < (OrigRuleCount-1); ++iTarget)
{
Rule = Rules[iTarget];
if(Rule->LeftFactor >= Length)
break;
}
//fprintf(stderr, ". select rule %d to left factor: ", iTarget);
//SymbolListDump(stderr, Rule->Symbols, " ");
//fprintf(stderr, "\n");
assert(Rule != NULL);
/* generate a new nonterminal to hold unique tails of nonunique left prefixes */
NewNonTerm = GenerateUniqueNonTerm(NonTerm, '#');
RuleMoveSuffix(Rule, Length, NewNonTerm);
RuleTruncate(Rule, Length);
RuleAddSymbol(Rule, NewNonTerm, EOFToken); /* no real token available, so use EOF */
/* NB: NRules may change during loop -- don't cache it in a local var! */
for(iRule = 0; iRule < RuleCount(NonTerm); ++iRule)
{
if(iRule == iTarget)
continue;
if(CommonLeft(NonTerm, Rule->Symbols, Rules[iRule]->Symbols) >= Length)
{
RuleMoveSuffix(Rules[iRule], Length, NewNonTerm);
RuleRemove(NonTerm, iRule);
--iRule;
}
}
/* must have removed at least one rule */
assert(RuleCount(NonTerm) < OrigRuleCount);
Rule->LeftFactor = 0; /* this rule can't be factored any more */
//fprintf(stderr, ". After left factoring, rule count = %d\n", NonTerm->NRules);
}
/* RewriteGrammar() - rewrite to attempt to achieve LL(1)ness.
*
* Here, we try to factor common left prefixes, and transform
* direct left recursion into LL(1) constructs. Note that previous
* code in checks.c have largely ignored these cases, so we
* have to do checking here to ensure the candidate rules really
* are something we can transform correctly and end up with an
* LL(1) grammar.
*/
void RewriteGrammar(void)
{
int NNonTerms, iTerm, iRule;
TSymbol* NonTerm;
SYMBOLS LeftRecurs = NULL;
SymIt NonTerms = SymItNew(Globals.NonTerms);
Dump(">RewriteGrammar().\n");
NNonTerms = SymbolListCount(Globals.NonTerms);
Dump(" remove immediate left recursion.\n");
while(SymbolIterate(&NonTerms))
{
SymbolListAddList(&LeftRecurs, LeftRecurSyms(NonTerms.Symbol, NULL, NULL));
}
printf("Found %d symbols involved in left recursion.\n", SymbolListCount(LeftRecurs));
SymbolListDump(stdout, LeftRecurs, " ");
#if 0
/* for each non-terminal... */
for(iTerm = 0; iTerm < NNonTerms; ++iTerm)
{
TRule** Left;
int NRules, NLeft, NNotLeft;
NonTerm = SymbolListGet(Globals.NonTerms, iTerm);
/* Only looking for valid left-recursive non-terminals */
if(NonTerm->OperatorTrigger || SymbolIsAction(NonTerm))
continue; /* then skip it */
NRules = RuleCount(NonTerm);
/* Left will be an array of the left-recursive rules */
Left = malloc(NRules * sizeof(TRule*));
/* for each rule of this non-terminal... */
for(NLeft = NNotLeft = iRule = 0; iRule < NRules; ++iRule)
{
int NProdItem;
TRule* Rule = NonTerm->Rules[iRule];
assert(Rule != NULL);
NProdItem = SymbolListCount(Rule->Symbols);
if(IsLeftRecursive(Rule, NonTerm))
Left[NLeft++] = Rule;
}
/* if we encountered one or more rules with immediate left-recursion */
#if 1
if(NLeft > 0)
RemoveLeftRecursion(NonTerm);
else
free(Left);
#endif
}
#endif
/* second, we rewrite to left factor the grammar */
if(Globals.Dump) printf(" left factor grammar.\n");
for(iTerm = 0; iTerm < SymbolListCount(Globals.NonTerms); ++iTerm)
{
int NRules;
int PrefixLen;
NonTerm = SymbolListGet(Globals.NonTerms, iTerm);
/* skip nonterminals irrelevant to rewriting */
if(NonTerm->OperatorTrigger || SymbolIsAction(NonTerm))
continue; /* then skip it */
NRules = RuleCount(NonTerm);
NumberCommonLeft(NonTerm);
PrefixLen = FindShortestPrefix(NonTerm);
for(iRule = 0; PrefixLen > 0; ++iRule)
{
assert(iRule < NRules);
RewriteCommonLeft(NonTerm, PrefixLen);
PrefixLen = FindShortestPrefix(NonTerm);
assert(iRule < NRules);
}
}
if(Globals.Dump) printf("<RewriteGrammar().\n");
//exit(0);
}
|
100siddhartha-blacc
|
compute.c
|
C
|
mit
| 51,284
|
#include "globals.h"
#include "parse.h"
#include "symtab.h"
#include "operator.h"
/* SyntaxPuts() - helper function for SyntaxError()
*
* Our lovely text error messages may come out all misaligned
* if the user has used tabs in a line that we're reporting in
* an error message. The best we can do is ask the user to tell
* us what tabstops they intended via the command-line '-t' option.
*
* Here, we print out a line, expanding any tab characters into
* a (hopefully) appropriate number of spaces. We also report how
* much we padded so that the caller can correctly point to the
* relevant token on the line.
*/
static
int SyntaxPuts(const char* Str, int Len)
{
int Padded = 0;
int Column = 0;
while(Len-- > 0)
{
if(*Str == '\t')
{
--Padded; /* first one doesn't count */
do {
fprintf(stderr, " ");
++Column;
++Padded;
} while(Column % 4);
}
else
fprintf(stderr, "%c", *Str);
++Str;
}
fprintf(stderr, "\n");
return Padded;
}
void SyntaxError(int ErrorCode, TToken Token, const char* Format, ...)
{
va_list ArgPtr;
TContext Context;
int LineNumber;
char* Buffer;
const char* Severity = ErrorCode ? "Error" : "Warning";
assert(Format != NULL);
Buffer = malloc(1024*8);
assert(Buffer != NULL);
Context = InputGetContext(Token.Text);
LineNumber = Context.LineNumber;
if(Context.LineNumber)
fprintf(stderr, "Line %d: %s %d.\n", Context.LineNumber, Severity, ErrorCode);
else
fprintf(stderr, "%s %d.\n", Severity, ErrorCode);
if(Context.LineLen == 0)
fprintf(stderr, "<EOF>\n");
else
{
int Padded;
size_t VisualLen, iDash;
Padded = SyntaxPuts(Context.LineStart, Context.LineLen);
// fprintf(stderr, "%.*s\n", Context.LineLen, Context.LineStart);
fprintf(stderr, "%*.0s^", (Token.Text - Context.LineStart) + Padded, " ");
for(VisualLen=0; VisualLen < Token.TextLen; ++VisualLen)
if(Token.Text[VisualLen] == '\r' || Token.Text[VisualLen] == '\n')
break;
for(iDash = 1; iDash < VisualLen-1; ++iDash)
fprintf(stderr, "-");
if(Token.TextLen > 1)
fprintf(stderr, "^");
fprintf(stderr, "\n");
}
assert(Format != NULL);
va_start(ArgPtr, Format);
vsprintf(Buffer, Format, ArgPtr);
va_end(ArgPtr);
if(!StrEndsWith(Buffer, "\n"))
strcat(Buffer, "\n");
fputs(Buffer, stderr);
if(LineNumber == 0)
LineNumber = -1;
if(ErrorCode)
Exit(LineNumber, ErrorCode);
}
/* AcceptLhs() - accept the left-hand side of a production.
*/
static
TSymbol* AcceptLhs(TToken Token)
{
TSymbol* Symbol;
Symbol = SymbolFind(Token);
if(Symbol) /* if this symbol already seen */
{
if(SymbolGetBit(Symbol, SYM_TERMINAL))
{
SyntaxError(ERROR_TERM_USED_AS_NONTERM, Token,
"Expecting a non-terminal to start a production, "
"but '%.*s' was previously defined as a terminal.\n",
Symbol->Name.TextLen, Symbol->Name.Text);
}
else
{
assert(SymbolGetBit(Symbol, SYM_TERMINAL) == FALSE);
if(Symbol->Lhs.Text && Globals.Verbose)
{
/* ??? report line previously defined on! */
SyntaxError(ERROR_NONE, Token,
"Non-terminal previously defined. Legal, but mildly unusual.\n");
}
}
}
else
{
Symbol = SymbolNewNonTerm(Token);
Symbol->Lhs = Token;
}
return Symbol;
}
/* ???TODO: define/handle a complete literal syntax here... */
static
int IsCharLiteral(TToken Token)
{
int Result = -1;
if(Token.TextLen >= 3 && Token.Text[0] == '\'' && Token.Text[Token.TextLen-1] == '\'')
{
if(Token.TextLen == 3)
Result = Token.Text[1];
else if(Token.TextLen == 4 && Token.Text[1] == '\\')
{
switch(Token.Text[2])
{
case 'b' : Result = '\b'; break;
case 'r' : Result = '\r'; break;
case 't' : Result = '\t'; break;
case '\'': Result = '\''; break;
case '\\': Result = '\\'; break;
case 'n' : Result = '\n'; break;
case 'f' : Result = '\f'; break;
}
}
}
return Result;
}
/* AcceptRhs() - accept a right-hand-side production item.
*
* On the right-hand side of a production, we just found either an
* identifier or a quoted string. If it's an identifier, then it's
* either a symbolic name for a terminal, or a non-terminal. If it's
* a quoted string, then it's an unnamed terminal.
*
* We return the TSymbol associated with Token (created or found).
*/
static
TSymbol* AcceptRhs(TToken LhsToken, TToken Token, TRule* Rule)
{
TSymbol* Symbol = NULL;
if(Token.Type == TK_IDENT || Token.Type == TK_QUOTED)
{
Symbol = SymbolFind(Token);
if(Symbol == NULL) /* if unknown identifier, presume non-terminal */
{
if(Token.Type == TK_IDENT)
Symbol = SymbolNewNonTerm(Token);
else if(Token.Type == TK_QUOTED)
{
int Value = IsCharLiteral(Token);
if(Value >= 0)
{
Symbol = SymbolNewTerm(Token);
SymbolSetValue(Symbol, Value);
}
else
{
Symbol = LiteralFind(Token);
if(Symbol == NULL)
{
TToken Clean = Unquote(Token);
SyntaxError(ERROR_UNDECL_LITERAL_IN_PROD, Token,
"Literal '%.*s' in production of '%.*s' should be "
"defined with a %%token declaration.\n",
Clean.TextLen, Clean.Text,
LhsToken.TextLen, LhsToken.Text);
}
}
}
else
assert(FALSE);
}
}
else
assert(FALSE);
RuleAddSymbol(Rule, Symbol, Token);
Symbol->UsedInRule = TRUE;
return Symbol;
}
/* ParseToken() - parse a token declaration.
*
* %token (ident literal?)+
*/
static
void ParseToken(TToken Token)
{
TSymbol* NewTerminal = NULL;
Token = InputPeekNext();
if(Token.Type != TK_IDENT && Token.Type != TK_QUOTED)
SyntaxError(ERROR_MISSING_NAME_IN_TOKEN_DECL, Token,
"Expecting identifier after '%token'.\n");
while(Token.Type == TK_QUOTED || Token.Type == TK_IDENT)
{
if(Token.Type == TK_QUOTED && NewTerminal == NULL)
SyntaxError(ERROR_MISSING_NAME_IN_TOKEN_DECL, Token,
"Missing token name in front of quoted string.\n");
if(Token.Type == TK_IDENT)
{
NewTerminal = SymbolFind(Token);
if(NewTerminal)
{
SyntaxError(ERROR_TERM_ALREADY_DEFINED, Token,
"'%.*s' was previously defined.\n",
Token.TextLen, Token.Text);
}
else
NewTerminal = SymbolNewTerm(Token);
}
else if(Token.Type == TK_QUOTED)
{
TSymbol* PreviousDef;
PreviousDef = LiteralFind(Token);
//??? Does this really work? Are we guaranteed that context of a token name will
//??? be the line it was first defined on?
if(PreviousDef)
{
TContext Previous;
Previous = InputGetContext(PreviousDef->Name.Text);
assert(Previous.LineNumber != 0);
SyntaxError(ERROR_LITERAL_ALREADY_DEFINED, Token,
"This literal was previously assigned a token name of '%.*s' on line %d:\n%.*s\n",
PreviousDef->Name.TextLen, PreviousDef->Name.Text,
Previous.LineNumber, Previous.LineLen, Previous.LineStart);
}
LiteralAdd(NewTerminal, Token);
NewTerminal = NULL;
}
InputGetNext(); /* eat token we already peeked at */
Token = InputPeekNext();
}
}
/* ParseStart() - parse declaration of starting non-terminal
*
* %token ident
*/
static
void ParseStart(TToken Token)
{
Token = InputPeekNext();
if(Token.Type != TK_IDENT)
{
SyntaxError(ERROR_EXPECTING_IDENT_AFTER_START, Token,
"Expecting a non-terminal name after %%start!\n");
}
else
{
TSymbol* Symbol = SymbolNewNonTerm(Token);
InputGetNext();
SymbolAddStart(Symbol);
/* ??? check for already a start symbol! */
}
/* ??? Not done - must do something with start decl!!! */
}
/* ParseOperand() - parse operand declaration
*
* %operand ident*
*/
static
void ParseOperand(TToken Token)
{
TSymbol* NewTerminal = NULL;
Token = InputPeekNext();
while(Token.Type == TK_IDENT)
{
NewTerminal = SymbolFind(Token);
if(NewTerminal == NULL)
NewTerminal = SymbolNewTerm(Token);
NewTerminal->Operand = TRUE;
InputGetNext(); /* eat token we already peeked at */
Token = InputPeekNext();
}
}
/* OperatorToSymbol() - from a token representing an operator, produce a TSymbol
*
* An operator declaration might look like this:
* %left X++
* When we encounter the '++', if it's not already been defined as
* a token literal like this:
* %token TK_SOMETHING_OR_OTHER '++'
* we will look up the corresponding token. We will also implicitly
* create the token if necessary if it's a single-character literal.
* Finally, if it's a multi-character literal and not already defined,
* then that's a syntax error.
*/
static
TSymbol* OperatorToSymbol(TToken Token)
{
TSymbol* Result;
/* maybe it's an already defined literal */
Result = LiteralFind(Token);
if(Result == NULL && Token.TextLen == 1) /* if it's not a defined literal */
{
TToken OpToken = TokenFake(TK_QUOTED, "'%.*s'", Token.TextLen, Token.Text);
Result = SymbolFind(OpToken);
if(Result == NULL)
{
Result = SymbolNewTerm(OpToken);
SymbolSetValue(Result, Token.Text[0]);
}
/* else, we wasted a few bytes of memory that won't get
* freed up until InputDestroy() gets called.
*/
}
return Result;
}
/* OperatorConflict() - Check for conflicts in operator declarations
*
* Operator homonyms allowed (once):
* - .X and X.
* - .X and X.X
* - .X., X.X. and .X.X
*/
static
int OperatorConflict(TOperator* Old, TOperator* New)
{
SYMBOLS OldList, NewList;
int NOld, NNew, iOld, iNew;
int Dup;
TSymbol* OldSym;
TSymbol* NewSym;
OldList = Old->List;
NOld = SymbolListCount(OldList);
NewList = New->List;
NNew = SymbolListCount(NewList);
Dup = 0;
for(iOld = 0; iOld < NOld && !Dup; ++iOld)
{
OldSym = SymbolListGet(OldList, iOld);
if(OldSym) /* NULL means operand placeholder */
{
for(iNew = 0; iNew < NNew; ++iNew)
{
NewSym = SymbolListGet(NewList, iNew);
if(NewSym == OldSym)
{
Dup = TRUE;
break;
}
}
}
}
return Dup;
}
/* ParseOperator() - parse an operator pattern from an operator precedence decl
*/
static
void ParseOperator(int Precedence, int Associativity, TToken Token, int MarkChar)
{
int NSymbols, NOperators, iOperator;
SYMBOLS List = NULL;
const char* Sentinel = Token.Text + Token.TextLen;
const char* Rover = Token.Text;
char Pattern[MAX_OPERATOR_PATTERN+1];
int IsQuoted = FALSE;
int OperandCount = 0;
if(*Rover == '\'' || *Rover == '"')
if(Token.TextLen > 1 && *Rover == Token.Text[Token.TextLen-1])
IsQuoted = TRUE;
Pattern[0] = '\0';
for(NSymbols = 0; Rover < Sentinel; ++NSymbols)
{
if(*Rover == MarkChar) /* if it's an operand placeholder */
{
List = SymbolListAdd(List, NULL);
strcat(Pattern, "X");
++Rover;
++OperandCount;
}
else
{
TToken Operator;
TSymbol* Symbol;
char Buffer[128];
Operator.Text = Rover;
while(Rover < Sentinel && *Rover != MarkChar)
++Rover;
Operator.TextLen = Rover - Operator.Text;
Operator.Type = TK_OPERATOR;
Symbol = OperatorToSymbol(Operator);
if(Symbol == NULL)
{
strcpy(Buffer, "This operator was not defined with a %%token declaration.");
if(Operator.Text[0] == '/')
strcat(Buffer, "\n(Note that comments are not allowed in a precedence declaration)\n");
else if(IsQuoted)
strcat(Buffer, "\n(Note that you should not quote operator patterns)\n");
SyntaxError(ERROR_UNDEFINED_OPERATOR, Operator, Buffer);
}
if(SymbolListContains(List, Symbol))
{
SyntaxError(ERROR_DUP_SYM_IN_OPERATOR, Operator,
"Same symbol used twice in one operator.\n");
}
List = SymbolListAdd(List, Symbol);
strcat(Pattern, ".");
}
if(strlen(Pattern) >= MAX_OPERATOR_PATTERN)
{
SyntaxError(ERROR_OP_DECL_TOO_LONG, Token,
"This operator declaration is too darned long."
);
}
}
if(OperandCount <= 0)
SyntaxError(ERROR_MISSING_OPERAND_IN_DECL, Token,
"Missing operand in operator declaration (operands are denoted by an 'X').\n");
else if(!PatternCmp("^.*X$", Pattern) && Associativity == TK_LEFT)
SyntaxError(ERROR_PREFIX_UNARY_DECL_LEFT, Token,
"Prefix unary operators cannot be declared left-associative.\n");
else if(!PatternCmp("X*.$", Pattern) && Associativity == TK_RIGHT)
SyntaxError(ERROR_POSTFIX_UNARY_DECL_RIGHT, Token,
"Postfix unary operators cannot be declared right-associative.\n");
else if(!PatternCmp("^.*.$", Pattern) && Associativity != TK_NONASSOC)
SyntaxError(ERROR_MUST_BE_NONASSOC, Token,
"Bracketing operators must be declared non-associative.\n");
OperatorAdd(Token, Precedence, Associativity, List, Pattern);
/* see if this conflicts with previous operator declarations */
NOperators = OperatorCount();
for(iOperator = 0; iOperator < NOperators-1; ++iOperator)
{
#if 0
TOperator* PrevOp = OperatorGet(iOperator);
/* ???TODO */
if(OperatorConflict(PrevOp, NewOp))
SyntaxError(ERROR_DUPL_OP_DECL, Token,
"This declaration conflicts with previous declaration of: '%.*s'\n",
PrevOp->Decl.TextLen, PrevOp->Decl.Text);
#endif
}
}
/* ParsePrecedence() - parse a precedence declaration.
*
* %{left|right|nonassoc} (ident literal?)+
*/
static
void ParsePrecedence(TToken Direction)
{
static int Precedence = 1; /* precedence 0 reserved for $, so start at 1 */
int Associativity = Direction.Type;
int OperatorCount = 0;
TToken Token;
for(;;)
{
Token = InputGetNext();
if(Token.Type == TK_EOF)
SyntaxError(ERROR_EOF_IN_PREC, Token,
"Unexpected EOF encountered while processing precedence directive.\n");
else if(Token.Type == TK_NEWLINE)
break;
else if(Token.Type == TK_OPERATOR)
{
ParseOperator(Precedence, Associativity, Token, 'X');
++OperatorCount;
}
/* can't really happen, but defensive programming */
else
SyntaxError(ERROR_EXPECTING_OPERATOR_DECL, Token,
"Illegal token; expecting an operator declaration.\n");
}
if(OperatorCount == 0)
SyntaxError(ERROR_PREC_WITHOUT_OPERATORS, Direction,
"Precedence directive line contained no operators!\n");
++Precedence;
}
/* SkipTest() - skip over a %test declaration.
*
* We don't do anything with test data during the initial parsing phase,
* so this function just skips over a %test declaration, assuming it is
* syntactically correct.
*/
static
void SkipTest(TToken TestStart)
{
TSymbol* Symbol;
TToken Token;
// Token = InputGetLine();
// assert(Token.Type == TK_LINE);
Token = InputGetNext();
while(Token.Type != TK_TEST)
{
switch(Token.Type)
{
case TK_EOF :
SyntaxError(ERROR_EOF_IN_TEST, TestStart,
"Found no terminating '%test' for this test.");
break;
case TK_IDENT :
case TK_QUOTED :
if(Token.Type == TK_IDENT)
Symbol = SymbolFind(Token);
else
Symbol = LiteralFind(Token);
if(!Symbol)
SyntaxError(ERROR_UNDEF_SYMBOL_IN_TEST, Token,
"Undefined symbol inside %%test.");
else if(SymbolGetBit(Symbol, SYM_TERMINAL) == FALSE)
SyntaxError(ERROR_NONTERM_IN_TEST, Token,
"Only terminal symbols allowed in %%test data.");
break;
default:
SyntaxError(ERROR_BAD_TOKEN_IN_TEST, Token,
"Expecting terminal (literal or symbolic) inside %%test.");
}
Token = InputGetNext();
}
}
static
void ParseDeclarations()
{
TToken Token;
Dump("ParseDeclarations()\n");
Token = InputGetNext();
while(Token.Type != TK_SECTION)
{
if(Token.Type == TK_LEFT || Token.Type == TK_RIGHT || Token.Type == TK_NONASSOC)
ParsePrecedence(Token);
else if(Token.Type == TK_TOKEN)
ParseToken(Token);
else if(Token.Type == TK_OPERAND)
ParseOperand(Token);
else if(Token.Type == TK_TEST)
SkipTest(Token);
else if(Token.Type == TK_START)
ParseStart(Token);
else if(Token.Type == TK_CODE)
;/*???*/
else if(Token.Type == TK_EOF)
SyntaxError(ERROR_EOF_IN_PREC, Token,
"Unexpected EOF in declaration section.\n", Token.Type);
else
SyntaxError(ERROR_BAD_TOKEN_IN_DECL, Token,
"Unexpected token [%d] in declaration section.\n", Token.Type);
Token = InputGetNext();
}
#if 0
#endif
Dump("ParseDeclarations() returns\n");
}
/* FakeActionToken() - create a fake token that names an action.
*
* No matter where an action occurs, we create a new null non-terminal
* for it. This lets us treat embedded actions in rules more or less uniformly
* ("normal" actions just happen to occur at the end of the rule).
*/
static
TToken FakeActionToken()
{
int NActions;
char NameBuffer[32];
char* Name;
TToken Fake;
/* create fake name based on action # */
NActions = SymbolListCount(Globals.Actions);
sprintf(NameBuffer, "{A%d}", NActions+1);
#if 0
Action = NEW(TAction);
assert(Action != NULL);
Action->Number = NActions+1;
Action->Action = ActionToken;
#endif
Fake.Type = TK_IDENT;
Fake.TextLen = strlen(NameBuffer);
Name = malloc(Fake.TextLen+1);
strcpy(Name, NameBuffer);
Fake.Text = Name;
#if 0
Result = SymbolNewNonTerm(NonTermName);
Result->Action = Action;
Globals.Actions = SymbolListAdd(Globals.Actions, Result);
#endif
return Fake;
}
#if 0
static
void CheckRuleDup(TSymbol* Lhs, TRule* Rule)
{
int iRule, NRules;
TRule* NewRule;
NRules = Lhs->NRules;
#if 0
for(iRule = 0; iRule < NRules-1; ++iRule)
{
int iItem, jItem, NActions;
TRule* OldRule = Lhs->Rules[iRule];
iItem = jItem = NActions = 0;
while(iItem <
}
#endif
}
#endif
/* HandleAction() - handle a TK_ACTION token in a rule.
*
* There is a default action that gets reused for any rule that
* has no trailing action.
*/
static
void HandleAction(TToken LhsToken, TToken ActionToken, TRule* Rule)
{
int IsDefault;
TSymbol* Symbol;
TToken ActionName;
IsDefault = TokenEqual(ActionToken, DefActToken);
if(IsDefault)
ActionName = ActionToken;
else
ActionName = FakeActionToken();
/* turn action into a hidden non-terminal with an empty rule */
Symbol = AcceptRhs(LhsToken, ActionName, Rule);
assert(SymbolGetBit(Symbol, SYM_TERMINAL) == FALSE);
if(Symbol->Action)
assert(IsDefault);
else
{
Symbol->Action = NEW(TAction);
assert(Symbol->Action != NULL);
Symbol->Action->Action = ActionToken;
Globals.Actions = SymbolListAdd(Globals.Actions, Symbol);
Symbol->Action->Number = SymbolListCount(Globals.Actions);
/* do not assign Action->ArgCount here, grammar rewriting may change it! */
/* nonterminal representing action gets a null rule */
SymbolNewRule(Symbol);
}
}
/* ParseInput() - parse input text, create data structures
*/
void ParseInput()
{
TToken Token;
TToken LhsToken;
ParseDeclarations();
Token.Type = TK_NOTUSED;
/* for each production (including alternatives) */
while(Token.Type != TK_EOF)
{
TSymbol* LHS;
TRule* Rule;
int iSymbol;
int LastTokenWasAction = FALSE;
if(Token.Type != TK_NONTERM)
Token = InputGetNext();
if(Token.Type == TK_EOF || Token.Type == TK_SECTION)
break;
else if(Token.Type != TK_NONTERM && Token.Type != TK_IDENT)
SyntaxError(ERROR_EXPECTING_NONTERM, Token,
"Expecting a non-terminal to start a production.");
LHS = AcceptLhs(Token);
if(SymbolStart() == NULL)
SymbolAddStart(LHS);
LhsToken = Token;
Token = InputGetNext();
if(Token.Type != ':')
SyntaxError(ERROR_EXPECTING_COLON, Token,
"Expecting ':' after non-terminal.");
if(Token.Type == '^')
{
LHS->Operand = TRUE;
LHS->OperatorTrigger = TRUE;
}
/* guarantee a rule, even if it's null */
Rule = SymbolNewRule(LHS);
/* for each alternative (including action) */
while(Token.Type != ';' && Token.Type != TK_NONTERM)
{
TSymbol* Symbol = NULL;
Token = InputGetNext();
LastTokenWasAction = (Token.Type == TK_ACTION);
/* while not at end-of-rule */
for(iSymbol=0; Token.Type != ';' && Token.Type != '|'; ++iSymbol)
{
/* if it's a terminal or non-terminal */
if(Token.Type == TK_IDENT || Token.Type == TK_QUOTED)
Symbol = AcceptRhs(LhsToken, Token, Rule);
/* if it's the lookahead operator (syntactic predicate) */
else if(Token.Type == '/')
{
if(iSymbol == 0)
SyntaxError(ERROR_NO_SYMBOL_BEFORE_SLASH, Token,
"In production for '%.*s': '/' must come after some symbol.");
/* ???TODO: check for multiple predicates even of different types */
assert(Symbol != NULL);
Symbol->PredicateEnd = TRUE;
Rule->Predicate = TRUE;
}
else if(Token.Type == TK_ACTION)
HandleAction(LhsToken, FakeActionToken(), Rule);
else
SyntaxError(ERROR_EXPECTING_OR_SEMI, Token,
"In production for '%.*s': expecting non-terminal, "
"action, '|', '/', or ';'\n", LHS->Name.TextLen, LHS->Name.Text);
Token = InputGetNext();
}
if(!LastTokenWasAction)
HandleAction(LhsToken, DefActToken, Rule);
if(Token.Type == '|')
Rule = SymbolNewRule(LHS);
}
if(Token.Type != ';')
SyntaxError(ERROR_EXPECTING_SEMICOLON, Token,
"Expecting ';' to terminate production list.");
}
if(Token.Type == TK_SECTION)
Token = InputGetNext();
if(Token.Type == TK_PROGRAM)
Globals.ProgramSection = Token;
else if(Token.Type == TK_EOF)
;
else
assert(FALSE);
}
|
100siddhartha-blacc
|
parse.c
|
C
|
mit
| 27,066
|
/* main.cpp - entry point for BLACC (Burk Labs' Anachronistic Compiler Compiler)
*
* BLACC is designed to be a parser generator that I can easily bend
* to whatever inconvenient need I have.
*/
#include "common.h"
#include "lex.h"
#include <stdio.h>
#include <thread>
#include <stack>
static TTokenizedFile PrepareInputTokens(Lex* ThisLex, const char* GrammarFilename,
TToken IncludeToken);
static unsigned int HardwareConcurrency(void);
int main(int ArgCount, char** Args)
{
const char* GrammarFilename;
// TToken NullToken = {nullptr, 0, 0};
// _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// parse command-line so we can get an input file
Global::ParseArgs(ArgCount, Args);
printf("# of threads = %u\n", HardwareConcurrency());
unique_ptr<Lex> ThisLex(new Lex);
GrammarFilename = Global::InputFilename();
if(!GrammarFilename)
Usage("Missing name of input file.\n");
TTokenizedFile GrammarFile =
PrepareInputTokens(ThisLex.get(), Global::InputFilename(), TToken::Null);
}
/* PrepareInputTokens() - Get to the point we have a set of input tokens ready to parse.
*
* This function will, if it encounters no errors, completely tokenize all of the
* input of the designated input file, as well as all files it %include's.
****************************************************************************************/
static TTokenizedFile PrepareInputTokens(Lex *ThisLex, const char* GrammarFilename,
TToken IncludeToken)
{
int TokenErrors;
// read the input file
TTokenizedFile GrammarFile = ThisLex->FileLoad(GrammarFilename, IncludeToken);
TokenErrors = GrammarFile->Tokenize();
if(TokenErrors > 0)
{
if(TokenErrors > 1)
printf("%d error tokens in '%s'\n", TokenErrors, Global::InputFilename());
}
else
{
// scan token list for valid %include directives
for(auto TokenIter=GrammarFile->Begin(); TokenIter != GrammarFile->End(); ++TokenIter)
{
if(TokenIter->Type == Lex::INCLUDE && TokenIter[1].Type == Lex::QUOTED)
{
unique_ptr<char> Filename(TokenIter[1].Unquote());
if(!ThisLex->Loaded(Filename.get()))
ThisLex->FileLoad(Filename.get(), TokenIter[0]);
}
}
}
return GrammarFile;
}
/* HardwareConcurrency() - How much parallelism does the hardware have?
*
* Due to a very painful bug in Visual C++, we use a wrapper function for
* what should be a simple library call.
*/
static unsigned int HardwareConcurrency(void)
{
static unsigned int ThreadCount;
if(ThreadCount == 0)
{
#ifdef _MSC_VER // compiler believes catch unreasonable (true if there were no bug)
# pragma warning(push)
# pragma warning(disable:4702)
#endif
try {
ThreadCount = std::thread::hardware_concurrency();
}
catch (...)
{
fprintf(stderr,
"Can't happen: hardware_concurrency() threw an exception.\n"
"Are you running under Windows/AppVerifier with HighVersionLie checked?\n"
"If so, you may want to do something like:\n"
" appverif -disable HighVersionLie -for blacc.exe\n"
);
throw;
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif
// note that 0 is essentially "don't know"
if(ThreadCount == 0)
ThreadCount = 1;
}
return ThreadCount;
}
|
100siddhartha-blacc
|
main.cpp
|
C++
|
mit
| 3,728
|
/* input.c - various functions related to BLACC's input.
*/
#include "input.h"
#include <ctype.h>
#include "loadfile.h"
#include "javascrp.h"
typedef struct TInput
{
const char* Filename;
char* FileText;
char* FileEnd;
int LineNumber;
const char* Rover;
int Peeked;
TToken Token;
int State;
size_t iNextToken;
TToken* Master;
size_t MasterLen;
size_t MasterCap;
int SectionCount; /* how many %%'s have we seen? */
} TInput;
TInput Input;
TToken EOFToken = {TK_EOF, "BLC_EOF", 7};
TToken StartToken = {TK_START, "<start>", 7};
//TToken EOLToken = {TK_EOL, "BLC_EOL", 7};
TToken MatchAnyToken = {TK_MATCHANY, "BLC_MATCHANY", 12};
TToken NoActionToken = {TK_MATCHANY, "BLC_NOACTION", 12};
TToken ReduceToken = {TK_IDENT, "{}", 2};
TToken DefActToken = {TK_IDENT, "{A0}", 4};
static
TToken InputGetNextInternal();
/* TokenFake() - create a fake TToken.
*
* Sometimes it is convenient to introduce things that were not
* explicitly a part of the input grammar. This function makes it
* easy to create a TToken that wasn't actually in the input stream.
*
* Mostly just to get clean memory debugging, we track every
* fake token we allocate so we can free it up in InputDestroy();
*/
typedef struct TFakeList
{
struct TFakeList* Next;
char* Text;
} TFakeList;
static
TFakeList* FakeList;
TToken TokenFake(int Type, const char* Format, ...)
{
TToken Result;
char* Buffer;
va_list Args;
TFakeList* Item;
Buffer = malloc(1024 * 16);
assert(Buffer != NULL);
va_start(Args, Format);
vsprintf(Buffer, Format, Args);
va_end(Args);
Result.Type = Type;
Result.TextLen = strlen(Buffer);
Result.Text = realloc(Buffer, Result.TextLen+1);
assert(Result.Text != NULL);
/* track allocation for later freeing */
Item = NEW(TFakeList);
assert(Item != NULL);
Item->Text = (char*)Result.Text;
Item->Next = FakeList;
FakeList = Item;
return Result;
}
int InputIsFake(TToken Token)
{
return !(Token.Text >= Input.FileText && Token.Text < Input.FileEnd);
}
int TokenEqual(TToken A, TToken B)
{
int Result = FALSE;
if(A.TextLen == B.TextLen)
if(!strncmp(A.Text, B.Text, A.TextLen))
Result = TRUE;
return Result;
}
static
void AddToken(TToken Token)
{
/* if we need to grow master token list */
if(Input.MasterLen >= Input.MasterCap)
{
Input.MasterCap+= 510;
Input.Master = realloc(Input.Master, Input.MasterCap*sizeof(TToken));
assert(Input.Master != NULL);
}
Input.Master[Input.MasterLen++] = Token;
}
/* InputDestroy() - free up memory.
*
* Try to free up everything we can, to make the memwatch
* log more useful.
*/
void InputDestroy(void)
{
TFakeList* Rover;
TFakeList* Temp;
if(Input.Filename)
free((void*)Input.Filename);
if(Input.FileText)
free(Input.FileText);
if(Input.Master)
free(Input.Master);
for(Rover=FakeList; Rover; )
{
Temp = Rover->Next;
free(Rover->Text);
free(Rover);
Rover = Temp;
}
}
int InputCreate(const char* Filename)
{
static int Initialized=FALSE;
int Errors;
char* FileText;
if(!Initialized)
{
EOFToken = TokenFake(TK_EOF, "BLC_EOF");
StartToken = TokenFake(TK_START, "<start>");
// EOLToken = TokenFake(TK_EOL, "BLC_EOL");
MatchAnyToken = TokenFake(TK_MATCHANY, "BLC_MATCHANY");
NoActionToken = TokenFake(TK_MATCHANY, "BLC_MATCHANY");
ReduceToken = TokenFake(TK_IDENT, "{}");
Initialized = TRUE;
}
FileText = LoadFile(Filename);
assert(FileText != NULL);
Dump("back from LoadFile('%s')\n", Filename);
Input.LineNumber = 1;
Input.FileText = FileText;
Input.Rover = FileText;
Input.Filename = StrClone(Filename);
Input.FileEnd = FileText + strlen(FileText);
Input.State = 0; /* normal state (everywhere but precedence decls) */
Input.iNextToken = 0;
Input.SectionCount = 0;
Input.MasterLen = 0;
Input.MasterCap = 510;
Input.Master = (TToken*)malloc(Input.MasterCap*sizeof(TToken));
assert(Input.Master != NULL);
for(Errors=0;;)
{
TToken Token = InputGetNextInternal();
AddToken(Token);
switch(Token.Type)
{
case TK_ILLEGAL:
case TK_BADQUOTE:
++Errors;
break;
case TK_SECTION:
if(Input.SectionCount == 2 && Input.Rover[0] != '\0')
Input.State = 99;
break;
}
if(Token.Type == TK_EOF)
break;
}
Dump("InputCreate() returns %d\n", Errors);
return Errors;
}
static
const char* SkipWhiteSpace(const char* Rover, int NewLinesToo)
{
const char* Skip;
TToken Token;
Token.Text = Rover;
Skip = NewLinesToo ? " \t\r\n" : " \t";
while(*Rover && strchr(Skip, *Rover))
++Rover;
if(Rover > Token.Text)
{
Token.TextLen = Rover - Token.Text;
Token.Type = TK_WHITESPACE;
AddToken(Token);
}
return Rover;
}
static
const char* SkipCommentLine(const char* Rover)
{
TToken Token;
assert(Rover[0] == '/' && Rover[1] == '/');
Token.Type = TK_COMMENT;
Token.Text = Rover;
for(Rover+= 2; *Rover; ++Rover)
if(*Rover == '\n')
break;
Token.TextLen = Rover - Token.Text;
AddToken(Token);
return Rover;
}
static
const char* SkipComment(const char* Rover)
{
TContext Context;
TToken Token;
assert(Rover[0] == '/' && Rover[1] == '*');
Context = InputGetContext(Rover);
Token.Type = TK_COMMENT;
Token.Text = Rover;
for(Rover+=2; *Rover; ++Rover)
if(Rover[0] == '*' && Rover[1] == '/')
break;
if(*Rover)
Rover += 2;
else
{
fprintf(stderr, "Line %d: unexpected EOF in comment that started here.\n",
Context.LineNumber);
Exit(Context.LineNumber, ERROR_EOF_IN_COMMENT);
}
Token.TextLen = Rover - Token.Text;
AddToken(Token);
return Rover;
}
/* SkipStuff() - skip whitespace and comments.
*/
static
void SkipStuff()
{
const char* Rover;
const char* OldRover;
Rover = Input.Rover;
OldRover = Rover;
for(;;)
{
Rover = SkipWhiteSpace(Rover, TRUE);
if(Rover[0] == '/')
{
if(Rover[1] == '*')
Rover = SkipComment(Rover);
else if(Rover[1] == '/')
Rover = SkipCommentLine(Rover);
}
if(Rover == OldRover)
break;
else
OldRover = Rover;
}
Input.Rover = Rover;
}
/* GetCPreCode() - gather up C/C++ code inside %{...%}
*
* ??? crude version. Rework later...
*/
static
TToken GetCPreCode(const char** RoverPtr)
{
TToken Result;
const char* Rover = *RoverPtr;
Result.Text = Rover;
++Rover; /* skip '{' */
while(*Rover && (*Rover != '%' || Rover[1] != '}'))
++Rover;
if(*Rover)
{
Result.Type = TK_CODE;
*RoverPtr = Rover+2;
Result.TextLen = *RoverPtr - Result.Text;
}
else
{
Result.Type = TK_ILLEGAL;
*RoverPtr = Rover;
Result.TextLen = Rover - Result.Text;
}
return Result;
}
/* GetNextToken() - identify and return the next token in the input
*
* Note that we are always operating on an in-memory copy of the original
* input file.
*/
static
TToken GetNextToken()
{
TToken Token;
const char* Rover;
int Char;
if(Input.State == 0)
SkipStuff();
Rover = Input.Rover;
Token.Type = TK_NOTUSED;
Token.Text = Rover; /* Should be at start of some token now */
Token.TextLen = 1; /* assume it's one byte long for now */
if(Input.State == 0) /* if normal token processing in effect */
switch((Char=*Rover++))
{
case '\0' :
Token.Type = TK_EOF;
--Rover;
break;
case '^' :
if(*Rover == ':')
{
++Rover;
++Token.TextLen;
}
case ':' :
case '|' :
case ';' :
case '/' :
Token.Type = Char;
break;
case '@' :
Token.Type = TK_MATCHANY;
break;
default:
if(Char == '%')
{
if(*Rover == '%')
{
Token.Type = TK_SECTION;
++Rover;
++Token.TextLen;
++Input.SectionCount;
}
else if(*Rover == '{')
{
Token = GetCPreCode(&Rover);
}
else
{
while(isalpha(*Rover))
++Rover;
Token.TextLen = Rover - Token.Text;
if(Token.TextLen == 5 && !strncmp("%left", Token.Text, 5))
Token.Type = TK_LEFT, Input.State = 1;
else if(Token.TextLen == 6 && !strncmp("%right", Token.Text, 6))
Token.Type = TK_RIGHT, Input.State = 1;
else if(Token.TextLen == 9 && !strncmp("%nonassoc", Token.Text, 9))
Token.Type = TK_NONASSOC, Input.State = 1;
else if(Token.TextLen == 6 && !strncmp("%token", Token.Text, 6))
Token.Type = TK_TOKEN;
else if(Token.TextLen == 8 && !strncmp("%operand", Token.Text, 8))
Token.Type = TK_OPERAND;
else if(Token.TextLen == 5 && !strncmp("%test", Token.Text, 5))
Token.Type = TK_TEST;
else if(Token.TextLen == 6 && !strncmp("%start", Token.Text, 6))
Token.Type = TK_START;
else
Token.Type = TK_ILLEGAL;
}
}
// ??? This section not done (handle comments, etc.)
else if(Char == '{')
{
int BraceCount = 1;
int State = 0;
int Done = FALSE;
for(Done = FALSE; !Done && BraceCount > 0; ++Rover)
{
switch(State)
{
case 0: /* normal, initial state */
switch(*Rover)
{
case '\0': Done = TRUE; break;
case '}' : --BraceCount; break;
case '\'': State = 1; break;
case '\"': State = 2; break;
case '/' :
if(Rover[1] == '/')
State = 3;
else if(Rover[1] == '*')
State = 4;
break;
}
break;
case 2: /* processing string quote */
switch(*Rover)
{
case '\0': Done = TRUE; break;
case '"' : State = 0; break;
case '\\':
if(Rover[1] == '"')
++Rover;
break;
}
break;
}
}
if(BraceCount <= 0)
{
Token.Type = TK_ACTION;
Token.TextLen = Rover - Token.Text;
}
}
else if(Char == '\'')
{
Token.Type = TK_QUOTED;
Token.TextLen = 1;
while(*Rover != '\'' && *Rover != '\0' && *Rover != '\n')
{
if(*Rover == '\\')
{
if(Rover[1] == '\'')
++Rover;
}
++Rover;
}
if(*Rover == '\'')
{
++Rover;
Token.TextLen = Rover - Token.Text;
}
else
Token.Type = TK_BADQUOTE;
}
else if(isalpha(Char) || Char == '_' || Char == '.')
{
while(isalnum(*Rover) || *Rover == '_' || *Rover == '.')
++Rover;
Token.Type = TK_IDENT;
Token.TextLen = Rover - Token.Text;
}
else
Token.Type = TK_ILLEGAL;
}
else if(Input.State == 1) /* else State!=0, must be processing precedence decls */
{
/* skip leading white space */
Rover = SkipWhiteSpace(Rover, FALSE);
// while(*Rover == ' ' || *Rover == '\t')
// ++Rover;
Token.Text = Rover;
if(*Rover == '\n')
{
Token.Type = TK_NEWLINE;
++Rover;
Input.State = 0; /* back to normal processing*/
}
else if(*Rover == '\0')
{
Token.TextLen = 0;
Token.Type = TK_EOF;
Input.State = 0; /* back to normal processing (if any!) */
}
else
{
while(!strchr(" \t\n", *Rover))
++Rover;
Token.TextLen = Rover - Token.Text;
Token.Type = TK_OPERATOR;
}
}
else if(Input.State == 99) /* gathering program section */
{
while(*Rover != '\0')
++Rover;
--Rover;
Token.TextLen = Rover - Token.Text;
Token.Type = TK_PROGRAM;
Input.State = 0;
}
Input.Rover = Rover;
assert(Token.Type != TK_NOTUSED);
return Token;
}
/* InputGetLine() - get the rest of the current input line as a token.
*
* The rest of the current line will be returned as though it were a
* token. The terminating character could be carriage return, newline,
* or EOF. Any end-of-line sequence will be skipped over, but not returned
* as part of the token.
*/
TToken InputGetLine()
{
const char* Rover;
TToken Result;
/* handle case of peeked token */
if(Input.Peeked)
{
Input.Peeked = FALSE;
Rover = Input.Token.Text;
}
else
Rover = Input.Rover;
Result.Text = Rover;
while(*Rover != '\0' && *Rover != '\r' && *Rover != '\n')
++Rover;
Result.TextLen = Rover - Result.Text;
Result.Type = TK_LINE;
return Result;
}
/* InputGetNext() - get the next token.
*
* The input has already been completely tokenized, so all we
* do here is move forward in the token list until we find a token
* that is not a comment or whitespace.
*/
TToken InputGetNext()
{
int Done;
TToken Result;
if(Input.Peeked) /* if we have a lookahead token ready to go */
{
Input.Peeked = FALSE;
Result = Input.Token;
}
else
{
for(Done=FALSE; !Done;)
{
if(Input.iNextToken >= Input.MasterLen)
{
Result = EOFToken;
break;
}
else
Result = Input.Master[Input.iNextToken++];
switch(Result.Type)
{
default: Done = TRUE;
break;
case TK_COMMENT:
case TK_WHITESPACE:
break;
}
}
}
if(Result.Type == TK_IDENT)
{
unsigned iToken;
TToken NextToken;
iToken = Input.iNextToken;
while(iToken < Input.MasterLen)
{
NextToken = Input.Master[iToken++];
if(NextToken.Type == ':')
{
Result.Type = TK_NONTERM;
break;
}
else if(NextToken.Type == TK_COMMENT || NextToken.Type == TK_WHITESPACE)
continue;
else
break;
}
}
return Result;
}
TToken* InputGetTokens(void)
{
return Input.Master;
}
static
TToken InputGetNextInternal()
{
TToken Result;
if(Input.Peeked) /* if we have a lookahead token ready to go */
{
Input.Peeked = FALSE;
Result = Input.Token;
}
else
Result = GetNextToken();
#if 0
printf("'%.*s'\n", Result.TextLen, Result.Text);
#endif
assert(Result.Text >= Input.FileText);
return Result;
}
TToken InputPeekNext()
{
if(Input.Peeked == FALSE)
{
Input.Token = InputGetNext();
Input.Peeked = TRUE;
}
return Input.Token;
}
/* InputGetChar() - get a character from the input stream.
*
* Basically, this exists because the operator precedence specifications
* are funky and lie outside the much simpler normal tokenization
* syntax for the rest of the file. We handle any previously peeked
* token correctly on moral grounds; I'm not sure that case even arises
* in the code currently, though.
*/
int InputGetChar()
{
int Result = -1;
if(Input.Peeked) /* if we have a lookahead token ready to go */
{
Result = Input.Token.Text[0];
++Input.Token.Text;
if(--Input.Token.TextLen <= 0)
Input.Peeked = FALSE;
}
else
{
Result = *Input.Rover;
if(Result != 0)
++Input.Rover;
}
assert(Result != -1);
return Result;
}
/* InputPrecGetNext() - get next token on a precedence directive line.
*
* The input tokenization rules change in a precedence directive.
* A token at this point is any sequence that doesn't contain
* whitespace characters.
*/
TToken InputPrecGetNext()
{
const char* Rover;
TToken Token;
Rover = Input.Rover;
/* skip leading white space */
while(*Rover == ' ' || *Rover == '\t')
++Rover;
Token.Text = Rover;
if(*Rover == '\n')
{
Token.TextLen = 1;
Token.Type = TK_NEWLINE;
++Rover;
}
else if(*Rover == '\0')
{
Token.TextLen = 0;
Token.Type = TK_EOF;
}
else
{
while(!strchr(" \t\n", *Rover))
++Rover;
Token.TextLen = Rover - Token.Text;
Token.Type = TK_TOKEN;
}
Input.Rover = Rover;
return Token;
}
/* InputGetContext() - get a TContext from a pointer into the file text.
*
* For error messages, it's convenient to have the text of the entire line
* the error occured in, along with the line number. This function takes
* a pointer into the text from the input file and returns all that information
* in a TContext structure.
*/
TContext InputGetContext(const char* Text)
{
TContext Result;
const char* Rover;
assert(Text != NULL);
Rover = Input.FileText;
Result.LineNumber = 0;
Result.LineLen = 0;
if(Text >= Input.FileText && Text <= Input.FileEnd)
{
/* count line numbers from start to context point */
while(Rover <= Text)
{
/* if previous char was a newline */
if(Rover == Input.FileText || Rover[-1] == '\n')
{
++Result.LineNumber;
/* remember where most recent line started */
Result.LineStart = Rover;
}
if(*Rover == '\0')
break;
++Rover;
}
/* locate the end of this line */
while(*Rover && Rover[-1] != '\n')
++Rover;
if(*Text == '\0') /* if context points to EOF */
{
Result.LineLen = 0;
}
else
{
assert(Rover >= Result.LineStart);
Result.LineLen = (Rover - Result.LineStart) - 1;
}
}
return Result;
}
#if 0
void InputError(INPUT Handle, const char* Text)
{
TInput* Input = (TInput*)Handle;
const char* LineStart;
assert(Handle != NULL);
assert(Text != NULL);
assert(Text > Input.FileText);
LineStart = Text;
while(LineStart > Input.FileText && *LineStart != '\n')
--LineStart;
}
#endif
//int InputGetLineNumber(INPUT Input, const char* Text);
//const char* InputGetLineStart(INPUT Input, const char* Text);
|
100siddhartha-blacc
|
input.c
|
C
|
mit
| 23,403
|
#ifndef INPUT_H_
#define INPUT_H_
#ifndef COMMON_H_
# include "common.h"
#endif
#define TK_EOF 0
#define TK_IDENT -1
#define TK_ACTION -2
#define TK_SECTION -3
#define TK_NOTUSED -4
#define TK_ILLEGAL -5
#define TK_QUOTED -6
#define TK_LEFT -7
#define TK_RIGHT -8
#define TK_NONASSOC -9
#define TK_TOKEN -10
#define TK_NEWLINE -11
#define TK_BADQUOTE -12 /* found a single quote, but not terminated */
#define TK_OPERAND -13
#define TK_TEST -14 /* %test [error# [line#]] */
#define TK_LINE -15 /* pseudo-token (rest of line) */
#define TK_START -16 /* pseudo-token (name of implicit start symbol */
#define TK_CODE -17 /* %{...%} */
#define TK_PROGRAM -18
#define TK_NONTERM -19 /* TK_IDENT followed by ':' */
//#define TK_EOL -25
#define TK_MATCHANY -26
#define TK_NOACT -27
#define TK_COMMENT -28
#define TK_WHITESPACE -29
#define TK_OPERATOR -30
typedef struct INPUT_
{
void* Dummy_;
} INPUT_, *INPUT;
typedef struct TToken
{
const char* Text;
size_t TextLen;
int Type;
} TToken;
typedef struct TContext
{
const char* LineStart;
int LineLen;
int LineNumber;
} TContext;
int TokenEqual(TToken A, TToken B);
TToken TokenFake(int Type, const char* Format, ...);
int InputCreate(const char* Filename);
void InputDestroy(void);
int InputIsFake(TToken Token);
TToken* InputGetTokens(void);
int InputGetChar(void);
TToken InputGetNext(void);
TToken InputGetLine(void);
TToken InputPrecGetNext(void);
TToken InputPeekNext(void);
TContext InputGetContext(const char* Text);
//void InputError(INPUT Input, const char* Text);
int InputGetLineNumber(const char* Text);
const char* InputGetLineStart(const char* Text);
extern TToken EOFToken;
extern TToken EOLToken;
extern TToken MatchAnyToken;
extern TToken NoActionToken;
extern TToken StartToken;
extern TToken ReduceToken;
extern TToken DefActToken; /* name of default action */
#endif
|
100siddhartha-blacc
|
input.h
|
C
|
mit
| 2,379
|
#ifndef JAVASCRP_H_
#define JAVASCRP_H_
/* javascrp.h - interface to storing information for later JavaScript emission.
*
*/
#ifndef INPUT_H_
#include "input.h"
#endif
enum JsClass
{
CLASS_SYMBOL = 0x0001,
CLASS_NONTERM = 0x0002,
CLASS_TERMINAL = 0x0004,
CLASS_COMMENT = 0x0008,
CLASS_ERROR = 0x0010,
};
void JsAdd(TToken Token);
void JsMarkClass(TToken Token, int Class);
void JsMarkId(TToken Token, int Id);
void JsWrite(const char* Filename);
#endif /* JAVASCRP_H_ */
|
100siddhartha-blacc
|
javascrp.h
|
C
|
mit
| 576
|
#ifndef SYMBOL_H_
#define SYMBOL_H_
/* symbol.h - define core data type.
*
* SYMBOL is an opaque pointer representing an instance of a symbol
* (terminal, non-terminal, or action). There may be one or more
* instances for a given symbol; an instance basically refers to a
* specific textual occurrence in the source grammar.
*/
#ifndef INPUT_H_
# include "input.h"
#endif
class SYMBOL
{
public:
~SYMBOL();
private:
SYMBOL(int Terminal);
static SYMBOL NewNonTerm(TToken Token);
static SYMBOL NewTerm(TToken Token);
};
typedef struct SYMBOLS_
{
void* Dummy_;
} SYMBOLS_, *SYMBOLS;
#endif /* SYMBOL_H_ */
|
100siddhartha-blacc
|
symbol.h
|
C++
|
mit
| 715
|
# GNUmakefile - Linux makefile for blacc
#
# last tested with G++ 4.6.3
CC = g++
CPPFLAGS = -std=c++0x -lintl
OBJS = main.o common.o microsoft.o globals.o file.o lex.o
EXENAME = blacc
all : $(EXENAME)
blacc : $(OBJS)
$(CC) -o $@ $^ $(LDFLAGS)
memcheck :
valgrind --leak-check=full ./blacc test.blc
$(OBJS) : common.h
|
100siddhartha-blacc
|
GNUmakefile
|
Makefile
|
mit
| 331
|
#ifndef PARSE_H_
#define PARSE_H_
#ifndef INPUT_H_
# include "input.h"
#endif
#ifndef SYMBOL_H_
# include "symtab.h"
#endif
/*extern TSymbol* StartSymbol; */
/* TSymbol* NonTermAdd(TToken Token); */
void ParseInput();
void SyntaxError(int ErrorCode, TToken Token, const char* Format, ...);
#endif /* PARSE_H_ */
|
100siddhartha-blacc
|
parse.h
|
C
|
mit
| 354
|
#include "common.h"
#include "globals.h"
#include "loadfile.h"
#include "html.h"
#include "htmlform.c"
/* TMacro - information about a macro invocation.
*
* We allow simple macro invocations of the form "@NAME@",
* where "NAME" is the name of a function (TFunc) in a table
* defined below. Macro invocations may also supply an argument,
* as with "@INCLUDE='file.ext'@"; the value inside the quoted
* string will be stored in TMacro.Value.
*/
typedef struct TMacro
{
const char* Name;
size_t NameLen;
char* Value;
} TMacro;
typedef void (*HTMLFUNC)(FILE* Output, TMacro* Macro);
typedef struct TFunc
{
const char* Name;
HTMLFUNC Func;
} TFunc;
/* htmlf() - a printf()-style function that escapes XML characters.
*
* (But not those appearing in the format string...) Geez, what
* a pain. Must've been an easier way I was too dumb to see.
*/
#define OP_EOS (0)
#define OP_GETARG (1)
#define OP_OUTINT (2)
#define OP_OUTLONG (3)
#define OP_OUTPTR (4)
typedef struct TMachine
{
int State;
char FmtSpec[32];
char* Output;
int IntArg;
const char* Input;
int DidDot;
} TMachine;
enum {STATE_START, STATE_START_FMT, STATE_PRE_ARG, STATE_ARG, STATE_DOT, STATE_SUFFIX};
static
int NextState(FILE* Output, TMachine* Machine)
{
int Type;
char Char;
for(;;)
switch(Machine->State)
{
case STATE_START:
Machine->Output = Machine->FmtSpec;
Machine->DidDot = FALSE;
Char = *Machine->Input++;
if(Char == '\0')
return OP_EOS;
else if(Char == '%')
{
*Machine->Output++ = Char;
Machine->State = STATE_START_FMT;
}
else /* else, literal character -- just spit it out */
fputc(Char, Output);
break;
case STATE_START_FMT: /* just saw '%' */
/* skip flags */
while(strchr("-+ #0", *Machine->Input))
*Machine->Output++ = *Machine->Input++;
/* fall through */
case STATE_PRE_ARG:
Char = *Machine->Input;
if(Char == '*')
{
++Machine->Input;
Machine->State = STATE_ARG;
return OP_GETARG;
}
while(isdigit(Char))
{
*Machine->Output++ = Char;
Char = *++Machine->Input;
}
Machine->State = Machine->DidDot ? STATE_SUFFIX : STATE_DOT;
break;
case STATE_ARG: /* caller just fetched an integer arg for us */
sprintf(Machine->Output, "%d", Machine->IntArg);
Machine->Output+= strlen(Machine->Output);
Machine->State = Machine->DidDot ? STATE_SUFFIX : STATE_DOT;
break;
case STATE_DOT: /* looking for optional '.' */
Char = *Machine->Input;
if(Char == '.')
{
*Machine->Output++ = *Machine->Input++;
}
Machine->DidDot = TRUE;
Machine->State = STATE_PRE_ARG;
break;
case STATE_SUFFIX:
Type = OP_OUTINT;
if(strchr("hlL", *Machine->Input))
{
if(*Machine->Input == 'l')
Type = OP_OUTLONG;
*Machine->Output++ = *Machine->Input++;
}
switch(*Machine->Input)
{
case 's' :
case 'p' :
Type = OP_OUTPTR;
break;
case 'c' :
case 'd' :
case 'u' :
break;
default:
assert(FALSE);
}
*Machine->Output++ = *Machine->Input++;
*Machine->Output = '\0';
Machine->State = STATE_START;
return Type;
default:
assert(FALSE);
}
}
#define INT_SPEC (1)
#define LONG_SPEC (2)
#define PTR_SPEC (3)
static void htmlf(FILE* Output, const char* Format, ...)
{
TMachine Machine = {STATE_START, 0};
int Opcode;
const char* Rover;
char* Buffer;
va_list ArgPtr;
Buffer = malloc(1024*8);
assert(Buffer != NULL);
assert(Format != NULL);
va_start(ArgPtr, Format);
Machine.Input = Format;
while((Opcode=NextState(Output, &Machine)) != OP_EOS)
{
if(Opcode == OP_EOS)
break;
else if(Opcode == OP_GETARG)
Machine.IntArg = va_arg(ArgPtr, int);
else
{
if(Opcode == OP_OUTINT)
sprintf(Buffer, Machine.FmtSpec, va_arg(ArgPtr, int));
else if(Opcode == OP_OUTLONG)
sprintf(Buffer, Machine.FmtSpec, va_arg(ArgPtr, long));
else if(Opcode == OP_OUTPTR)
sprintf(Buffer, Machine.FmtSpec, va_arg(ArgPtr, void*));
for(Rover=Buffer; *Rover; ++Rover)
switch(*Rover)
{
case '&' : fputs("&", Output); break;
case '<' : fputs("<", Output); break;
case '>' : fputs(">", Output); break;
case '\'' : fputs("'", Output); break;
case '\"' : fputs(""", Output); break;
default:
fputc(*Rover, Output);
}
}
}
#if 0
while(*Format)
{
switch(*Format)
{
case '%' :
Format = GetSpec(Format, Spec, &Type);
switch(Type)
{
case INT_SPEC :
IntArg = va_arg(ArgPtr, int);
sprintf(Buffer, Spec, IntArg);
break;
case LONG_SPEC :
LongArg = va_arg(ArgPtr, long);
sprintf(Buffer, Spec, LongArg);
break;
case PTR_SPEC :
PtrArg = va_arg(ArgPtr, void*);
sprintf(Buffer, Spec, PtrArg);
break;
default:
assert(FALSE);
}
break;
default:
fputc(*Format, Output);
}
++Format;
}
#endif
va_end(ArgPtr);
free(Buffer);
}
static
void HtmlInclude(FILE* Output, TMacro* Macro)
{
char* File;
if(Macro->Value)
{
File = LoadFile(Macro->Value);
fputs(File, Output);
free(File);
}
else
fprintf(stderr, "@INCLUDE@ macro requires argument naming file to include!\n");
}
static
void HtmlTitle(FILE* Output, TMacro* Macro)
{
ARGUNUSED(Macro);
fprintf(Output, "blacc: '%s'", Globals.InputFile);
}
static
void HtmlOperator(FILE* Output, TToken Token)
{
const char* Rover = Token.Text;
Dump("HtmlOperator(%d)\n", Token.TextLen);
htmlf(Output, "<span class='blc_op'>");
while(Rover < Token.Text + Token.TextLen)
{
if(*Rover == 'X')
htmlf(Output, "<span class='blc_X'>X</span>");
else
htmlf(Output, "%c", *Rover);
++Rover;
Dump("... \n");
}
htmlf(Output, "</span>");
Dump("HtmlOperator() returns\n");
}
static
void HtmlIllegalToken(FILE* Output, TToken Token)
{
const char* Rover = Token.Text;
Dump("HtmlIllegalToken(%d)\n", Token.TextLen);
htmlf(Output, "<span class='blc_illegal'>");
while(Rover < Token.Text + Token.TextLen)
{
htmlf(Output, "%c", *Rover);
++Rover;
}
htmlf(Output, "</span>");
Dump("HtmlIllegalToken() returns\n");
}
/* HtmlProgram() - emit any text that follows the second '%%'
*/
static
void HtmlProgram(FILE* Output, TMacro* Macro)
{
TToken* Rover = InputGetTokens();
ARGUNUSED(Macro);
while(Rover->Type != TK_EOF)
{
if(Rover->Type == TK_PROGRAM)
{
htmlf(Output, "%.*s",
Rover->TextLen, Rover->Text);
break;
}
++Rover;
}
}
static
void HtmlGrammar(FILE* Output, TMacro* Macro)
{
TToken* Rover = InputGetTokens();
ARGUNUSED(Macro);
while(Rover->Type != TK_EOF && Rover->Type != TK_PROGRAM)
{
switch(Rover->Type)
{
case TK_IDENT:
if(SymbolFind(*Rover))
htmlf(Output, "<span class='blc_sym'>%.*s</span>",
Rover->TextLen, Rover->Text,
Rover->TextLen, Rover->Text);
else
htmlf(Output, "<span>%.*s</span>",
Rover->TextLen, Rover->Text,
Rover->TextLen, Rover->Text);
break;
case TK_NEWLINE:
htmlf(Output, "<br/>\n");
break;
case TK_COMMENT:
htmlf(Output, "<span class='blc_cmnt'>%.*s</span>", Rover->TextLen, Rover->Text);
break;
case TK_OPERATOR:
HtmlOperator(Output, *Rover);
break;
case TK_ILLEGAL:
case TK_BADQUOTE:
HtmlIllegalToken(Output, *Rover);
break;
case TK_SECTION:
htmlf(Output, "<span class='blc_section'>%.*s</span>", Rover->TextLen, Rover->Text);
break;
case TK_LEFT:
case TK_RIGHT:
case TK_NONASSOC:
case TK_TEST:
case TK_START:
case TK_TOKEN:
htmlf(Output, "<span class='blc_kw'>%.*s</span>", Rover->TextLen, Rover->Text);
break;
default:
fprintf(Output, "%.*s", Rover->TextLen, Rover->Text);
}
++Rover;
}
}
static
TFunc Funcs[] =
{
{ "TITLE", HtmlTitle },
{ "GRAMMAR", HtmlGrammar },
{ "INCLUDE", HtmlInclude },
{ "PROGRAM", HtmlProgram },
// sentinel
{ NULL, NULL }
};
static
int IsQuote(int Char) { return (Char == '\'' || Char == '\"') ? Char : 0; }
static
//const char* IsMacro(const char* Rover)
const char* IsMacro(const char* Rover, TMacro* Macro)
{
int QChar, Char;
const char* Result = NULL;
const char* Value = NULL;
assert(*Rover == '@');
++Rover;
/* if it could be start of a macro */
if(isalpha(*Rover))
{
Macro->Name = Rover;
while(isalpha(*Rover)) /* skip possible macro name */
++Rover;
/* if it still could be a valid macro */
if(*Rover == '@' || *Rover == '=')
{
/* now we know the name length, if it turns out to be a macro */
Macro->NameLen = Rover - Macro->Name;
/* if macro name may have a value associated with it */
if(*Rover == '=' && (QChar = IsQuote(Rover[1])) != 0)
{
Rover += 2; /* skip '=' and quotation mark */
Value = Rover;
/* a doubled quote is an escape for a single quote */
while((Char =*Rover++) != '\0' && (Char != QChar || *Rover++ == QChar))
;
if(Char) /* if we found the matching end quote */
--Rover; /* we overshot, checking for a doubled quote */
if(*Rover == '@')
{
char* Output;
Macro->Value = Output = (char*)malloc(Rover-Value);
assert(Output != NULL);
for(;*Value != '@'; ++Value)
if(Value[0] == QChar && Value[1] == QChar)
*Output++ = *Value++;
else if(Value[0] == QChar)
{
*Output = '\0';
assert(Value[1] == '@');
}
else
*Output++ = *Value;
Result = Rover;
}
}
else if(*Rover == '@')
Result = Rover;
}
}
return Result;
}
/* Html() - output HTML that provides GUI for this grammar.
*
* We generate the output based on an internal template or an
* external file specified with the "-s" command-line option.
* The resulting template must contain @COMMAND@ items in it;
* these get replaced by particular generated code fragments.
* For example, @GRAMMAR@ contains HTML for the original
* grammar.
*/
typedef struct TInput
{
char* InStr;
const char* Rover;
struct TInput* Prev;
} TInput;
void Html(FILE* Output)
{
char* StyleFile;
const char* Rover = HtmlTemplate;
const char* Skip;
const char* Start;
int iFunc;
TInput* Input;
TMacro Macro = {0};
Input = NEW(TInput);
assert(Input != NULL);
Dump("Html() begins\n");
Rover = Input->InStr = HtmlTemplate;
if(Globals.StyleFile)
Rover = Input->InStr = StyleFile = LoadFile(Globals.StyleFile);
while(*Rover)
if(*Rover == '@' && (Skip=IsMacro(Rover, &Macro)) != NULL)
{
Dump("Found Macro '%.*s'\n", Macro.NameLen, Macro.Name);
for(iFunc=0; Funcs[iFunc].Name; ++iFunc)
if(!strncmp(Funcs[iFunc].Name, Macro.Name, Macro.NameLen))
{
Funcs[iFunc].Func(Output, &Macro);
break;
}
if(!Funcs[iFunc].Name)
{
fprintf(stderr, "Warning: unknown macro name ('%.*s') in HTML template.\n",
Macro.NameLen, Macro.Name);
}
if(Macro.Value)
{
free(Macro.Value);
Macro.Value = NULL;
}
Rover = Skip + 1;
}
/* we eat leading white space on line preceding a macro */
else if(isspace(*Rover))
{
Start = Rover;
while(isspace(*Start))
++Start;
if(*Start == '@' && IsMacro(Start, &Macro))
Rover = Start;
else
fputc(*Rover++, Output);
}
else
fputc(*Rover++, Output);
if(Globals.StyleFile)
free(Input->InStr);
free(Input);
Dump("Html() returns\n");
}
|
100siddhartha-blacc
|
html.c
|
C
|
mit
| 15,466
|
#ifndef FILE_H_
#define FILE_H_
#include <memory>
#include <string>
using namespace std;
class File
{
public:
File();
~File();
char* Load(const char* Filename);
private:
File(const File& Other); // disallow: private and no definition
File& operator=(const File& Other); // disallow: private and no definition
char* Buffer;
string Filename;
};
#endif /* FILE_H_ */
|
100siddhartha-blacc
|
file.h
|
C++
|
mit
| 457
|
#ifndef GENERATE_H_
#define GENERATE_H_
#ifndef SYMTAB_H_
#include "symtab.h"
#endif
#define BLC_HDR_TERMSYMTAB_SIZE (0)
#define BLC_HDR_NONTERMSYMTAB_SIZE (2)
#define BLC_HDR_ENTRYTABLE_SIZE (4)
#define BLC_HDR_SELECTTABLE_SIZE (6)
#define BLC_HDR_RULEOPCODE_SIZE (8)
#define BLC_HDR_SIZE (10)
typedef unsigned char BLC_OPCODE;
typedef struct INTVECTOR
{
int* v;
int Size;
} INTVECTOR;
typedef struct TParseTables
{
BLC_OPCODE* Opcodes;
int SelSectOfs;
int RuleSectOfs;
int NOpcodes;
size_t OpcodeSize;
INTVECTOR LLColumns; /* lists of terminals */
INTVECTOR LLRows; /* lists of rule numbers */
INTVECTOR LLRowStarts; /* offsets of row beginnings*/
INTVECTOR RuleOffsets; /* offsets into Opcodes */
int SelectStart; /* offset into SelectOffsets of start symbol */
int NRules;
TRule** Rules; /* list of unique rules */
SYMBOLS* RuleSymbols; /* parallel to Rules */
int MaxTokenVal;
int MinTokenVal;
SYMBOLS LLNonTerms;
int TokenMatchAny;
int TokenEol;
} TParseTables;
enum
{
BLCOP_MATCH =0x00, /* MATCH [token_id] */
BLCOP_CALL =0x01, /* CALL [16-bit rule offset] */
BLCOP_TAILSELECT=0x02, /* TAILSELECT [pop] [16-bit selset ofs] */
BLCOP_LLSELECT =0x03, /* LLSELECT [16-bit selset offset] */
BLCOP_ACTRED =0x04, /* ACTRED [action_id, reduce_count] */
BLCOP_REDUCE =0x05, /* REDUCE [reduce_count] */
BLCOP_HALT =0x06, /* HALT */
BLCOP_SHIFTSEL =0x07, /* SHIFTSEL */
BLCOP_ACTION8 =0x08, /* ACTION [action_id] */
};
TParseTables* GenerateParseTables(void);
void FreeParseTables(TParseTables* Tables);
#endif /* GENERATE_H_ */
|
100siddhartha-blacc
|
generate.h
|
C
|
mit
| 2,218
|
#ifndef LEX_H_
#define LEX_H_
#include "common.h"
#include <limits.h> // a pox on C++'s limits framework!
//#include <functional>
#include <map>
#include <memory>
#include <new>
#include <vector>
/* TToken - a token type.
*
* Tokens need to be relatively small and cheap since we will be storing
* them all in an array (per file) that stays in memory until blacc exits.
******************************************************************************/
struct TToken
{
const char* Text; // raw pointer into original file text
unsigned short TextLen; // # of bytes in this token (no NUL termination!)
short Type; // token type, as defined in Lex
enum{ MAXLEN = SHRT_MAX }; // maximum length for any token
static TToken Null;
int IsNull();
unique_ptr<char>Unquote() const;
};
typedef std::vector<TToken> TTokens;
typedef std::vector<TToken>::const_iterator TTokenIter;
typedef unique_ptr<std::vector<char>> TFileChars;
//class LexFile;
class Lex;
// FileLoad(): lowest-level function for loading a file.
unique_ptr<std::vector<char>> FileLoad(const char* Filename);
// LexFile: a file that will be loaded and tokenized.
class LexFile
{
public:
friend class Lex;
friend class Lexer;
int Tokenize();
TToken operator[](int Index) { return Tokens[Index]; }
TTokens GetTokens() { return Tokens; }
TTokenIter Begin() { return Tokens.begin(); }
TTokenIter End() { return Tokens.end(); }
~LexFile();
private:
LexFile(const char* Filename, TFileChars Text, TToken FromInclude);
// cruft for 'Tokens' unique_ptr vector
// struct Deleter{void operator()(LexFile*File) const {delete File;}};
LexFile(const LexFile& Other); // disallow: private and no definition
LexFile& operator=(const LexFile& Other); // disallow: private and no definition
std::string Filename; // name of file
TFileChars FileText; // must live as long as Tokens
TTokens Tokens; // array of tokens (result of tokenizing Buffer)
int ErrorCount; // # of error tokens in Tokens
TToken FromInclude; // parent file %include token (or NULL)
};
//typedef std::unique_ptr<LexFile> const &TTokenizedFile;
typedef LexFile *TTokenizedFile;
class Lexer
{
public:
Lexer(LexFile& RootFile);
~Lexer();
private:
};
class Lex
{
public:
Lex();
~Lex();
TTokenizedFile FileLoad(const char* Filename, TToken FromInclude);
TTokenizedFile Loaded(const char* Filename);
enum
{
TKEOF, // End-Of-File
IDENT, // [A-Za-z][A-Za-z0-9]+
ACTION, // { ... }
SECTION, // %%
QUOTED, // a quoted string
LEFT, // %left
RIGHT, // %right
NONASSOC, // %nonassoc
TOKEN, // %token
NEWLINE, // '\n'
OPERAND,
TEST, // %test
LINE,
START,
CODE,
PROGRAM,
NONTERM, // IDENT followed by ':'
MATCHANY,
NOACT,
COMMENT,
WHITESPACE,
OPERATOR,
ORBAR,
SEMICOLON,
NOTUSED, // useful for marking a token as not yet defined
// numbers > NOTUSED are all illegal tokens
TOOLONG, // token was too long
ILLEGAL, // didn't match any token type
UNKDIR, // unknown directive
BADQUOTE, // unterminated quote
INCLUDE, // %include
};
private:
std::map<std::string, std::unique_ptr<LexFile> > Files;
};
#endif
|
100siddhartha-blacc
|
lex.h
|
C++
|
mit
| 4,129
|
#include "common.h"
#include "symtab.h"
#include "generate.h"
#include "gen_c.h"
#include "map.h"
#include "globals.h"
#include <time.h>
/* include big char array named 'Template' */
#include "gen_ctmp.c"
#define HEXFLAG (0x01)
#define DECFLAG (0x00)
#define TWOFLAG (0x10)
#define ONEFLAG (0x00)
#define HEX16 (HEXFLAG|TWOFLAG)
#define HEX8 (HEXFLAG|ONEFLAG)
#define DEC16 (DECFLAG|TWOFLAG)
#define DEC8 (DECFLAG|ONEFLAG)
void VersionInsert(FILE* Output)
{
fprintf(Output, "0.0");
}
static
void FilenameInsert(FILE* Output)
{
fprintf(Output, "%s", Globals.InputFile);
}
static
void TimestampInsert(FILE* Output)
{
time_t Now;
Now = time(NULL);
fprintf(Output, "%s", asctime(localtime(&Now)));
}
#if 0
void RuleJumpsInsert(FILE* Output, TParseTables* Tables)
{
int iRule;
fprintf(Output, " ");
for(iRule = 0; iRule < Tables->RuleOffsets.Size; ++iRule)
{
if(iRule && !(iRule%10))
fprintf(Output, "\n ");
else
fprintf(Output, " ");
fprintf(Output, "%5d,", Tables->RuleOffsets.v[iRule]);
}
fprintf(Output, "\n");
}
void SelectJumpsInsert(FILE* Output, TParseTables* Tables)
{
int iSelect;
fprintf(Output, " ");
for(iSelect = 0; iSelect < Tables->SelectOffsets.Size; ++iSelect)
{
if(iSelect && !(iSelect%10))
fprintf(Output, "\n ");
else
fprintf(Output, " ");
fprintf(Output, "%5d,", Tables->SelectOffsets.v[iSelect]);
}
fprintf(Output, "\n");
}
void TranTypeDefInsert(FILE* Output, TParseTables* Tables)
{
fprintf(Output, "#if UCHAR_MAX >= %d\n", Tables->MaxTransitionInt);
fprintf(Output, " typedef unsigned char BLC_TRANS;\n");
fprintf(Output, "#elif USHRT_MAX >= %d\n", Tables->MaxTransitionInt);
fprintf(Output, " typedef unsigned short BLC_TRANS;\n");
fprintf(Output, "#elif UINT_MAX >= %d\n", Tables->MaxTransitionInt);
fprintf(Output, " typedef unsigned int BLC_TRANS;\n");
fprintf(Output, "#else\n");
fprintf(Output, " typedef unsigned long BLC_TRANS;\n");
fprintf(Output, "#endif\n");
}
#endif
/* TokenDefsInsert() - emit #defines for named terminals.
*/
void TokenDefsInsert(FILE* Output)
{
int iTerminal, NTerminals;
NTerminals = SymbolListCount(Globals.Terminals);
for(iTerminal = 0; iTerminal < NTerminals; ++iTerminal)
{
TSymbol* Terminal = SymbolListGet(Globals.Terminals, iTerminal);
assert(Terminal != NULL);
assert(SymbolGetBit(Terminal, SYM_TERMINAL));
if(Terminal->Name.Text[0] != '\'')
fprintf(Output, "#define %.*s %*.s(%d)\n",
Terminal->Name.TextLen,
Terminal->Name.Text,
MAX(32 - Terminal->Name.TextLen, 1),
" ",
Terminal->Value
);
}
}
void TypeDefsInsert(FILE* Output, TParseTables* Tables)
{
fprintf(Output, "#if SCHAR_MAX >= %d && SCHAR_MIN <= %d\n",
Tables->MaxTokenVal, Tables->MinTokenVal);
fprintf(Output, " typedef signed char BLC_TOKVAL;\n");
fprintf(Output, "#elif SHRT_MAX >= %d && SHRT_MIN <= %d\n",
Tables->MaxTokenVal, Tables->MinTokenVal);
fprintf(Output, " typedef short BLC_TOKVAL;\n");
fprintf(Output, "#elif INT_MAX >= %d && INT_MIN <= %d\n",
Tables->MaxTokenVal, Tables->MinTokenVal);
fprintf(Output, " typedef int BLC_TOKVAL;\n");
fprintf(Output, "#else\n");
fprintf(Output, " typedef long BLC_TOKVAL;\n");
fprintf(Output, "#endif\n");
// fprintf(Output, "typedef int BLC_NEXTSTATE;\n");
fprintf(Output, "typedef unsigned char BLC_OPCODE;\n");
fprintf(Output, "typedef int BLC_VALTYPE;\n");
}
#if 0
void TransSizeInsert(FILE* Output, TParseTables* Tables)
{
fprintf(Output, "%d", Tables->TransitionsSize);
}
void ProdsSizeInsert(FILE* Output, TParseTables* Tables)
{
fprintf(Output, "%d", Tables->ProductionsSize);
}
#endif
void ValidTokensInsert(FILE* Output, TParseTables* Tables)
{
int iToken;
for(iToken = 0; iToken < Tables->LLColumns.Size; ++iToken)
fprintf(Output, "%d, ", Tables->LLColumns.v[iToken]);
}
void NextStatesInsert(FILE* Output, TParseTables* Tables)
{
int iState;
for(iState = 0; iState < Tables->LLRows.Size; ++iState)
fprintf(Output, "%d, ", Tables->LLRows.v[iState]);
}
static
int Load8(unsigned char* Opcodes, int* IP)
{
int Result;
Result = Opcodes[*IP] & 0x0FF;
++*IP;
assert(Result >= 0);
return Result;
}
static
int Load16(unsigned char* Opcodes, int* IP)
{
int Result;
Dump("Load16(%d)\n", *IP);
Result = Opcodes[*IP] & 0x0FF;
++*IP;
Result = Result | ((Opcodes[*IP] & 0x0FF) << 8);
++*IP;
assert(Result >= 0);
Dump("Load16() returns %d\n", Result);
return Result;
}
/* TokenStr() - fetch string version of token from token value
*/
static
const char* TokenStr(int TokenVal)
{
const char* Result = NULL;
SymIt Terminal;
Terminal = SymItNew(Globals.Terminals);
while(SymbolIterate(&Terminal))
if(Terminal.Symbol->Value == TokenVal)
{
Result = SymbolStr(Terminal.Symbol);
break;
}
if(Result == NULL)
{
fprintf(stderr, "%d is not a valid token value!\n", TokenVal);
assert(Result != NULL);
}
return Result;
}
static
void EmitAddress(FILE* Output, int IP, const char* Format, ...)
{
va_list ArgPtr;
fprintf(Output, "/*0x%04X: ", IP);
va_start(ArgPtr, Format);
vfprintf(Output, Format, ArgPtr);
va_end(ArgPtr);
fprintf(Output, " */\n");
}
static
void Emit(FILE* Output, int Flag, int Value, const char*Format, ...)
{
size_t Len;
char* Buffer;
va_list ArgPtr;
Dump("Emit()\n");
Buffer = malloc(1024*4);
assert(Buffer != NULL);
if(Flag&TWOFLAG)
sprintf(Buffer, (Flag&HEXFLAG) ? " 0x%02X,0x%02X," : " %u,%u,",
Value & 0x0FF, (Value>>8)&0x0FF);
else
sprintf(Buffer, (Flag&HEXFLAG) ? " 0x%02X," : " %u,",
Value & 0x0FF );
Len = strlen(Buffer);
if(Len < 16)
Len = 16 - Len;
else
Len = 0;
fprintf(Output, "%s%*.*s", Buffer, Len, Len, "");
if(Format)
{
va_start(ArgPtr, Format);
vsprintf(Buffer, Format, ArgPtr);
va_end(ArgPtr);
fprintf(Output, "/* %s */\n", Buffer);
}
else
fprintf(Output, "\n");
free(Buffer);
Dump("Emit() returns\n");
}
static
int EmitSelectBody(FILE* Output, unsigned char* Opcodes, int IP)
{
int Count;
int OldIP;
/* first emit the token ranges */
Count = Load8(Opcodes, &IP);
OldIP = IP;
while(Count > 0)
{
int Start, End;
int Addr;
Emit(Output, DEC8, Count, "%d token ranges in this group", Count);
Addr = Load16(Opcodes, &IP);
Emit(Output, HEX16, Addr, "0x%04X: address of rule", Addr);
while(Count-- > 0)
{
Start = Load8(Opcodes, &IP);
End = Load8(Opcodes, &IP);
Emit(Output, DEC16, Start|(End<<8), "%s - %s", TokenStr(Start), TokenStr(End));
}
Count = Load8(Opcodes, &IP);
}
Emit(Output, DEC8, 0, (IP > OldIP) ? "EOL for token ranges" : "EOL (no token ranges)");
/* then emit the token groups */
Count = Load8(Opcodes, &IP);
OldIP = IP;
while(Count > 0)
{
int TokenId;
int Addr;
Emit(Output, DEC8, Count, "%d tokens for this rule", Count);
Addr = Load16(Opcodes, &IP);
Emit(Output, HEX16, Addr, "0x%04X: address of rule", Addr);
while(Count-- > 0)
{
TokenId = Load8(Opcodes, &IP);
Emit(Output, DEC8, TokenId, "%s", TokenStr(TokenId));
}
Count = Load8(Opcodes, &IP);
}
Emit(Output, DEC8, 0, (IP > OldIP) ? "EOL for token lists" : "EOL (no token lists)");
return IP;
}
/* ActionNote() - create an abbreviated comment about an action.
*
* We want to show part of the action in a comment.
*/
#define ACTNOTESIZE (64)
static
const char* ActionNote(TAction* Action)
{
static char Note[ACTNOTESIZE+1];
char* Rover;
const char* Input;
const char* Start;
size_t Len;
Rover = Note;
*Rover = '\0';
Input = Start = Action->Action.Text;
Len = Action->Action.TextLen;
while((Rover - Note) < ACTNOTESIZE)
{
switch(*Input)
{
case '\r' :
case '\n' :
case '\t' :
*Rover++ = ' '; ++Input;
while(isspace(*Input) && ((unsigned)(Input - Start)) < Len)
++Input;
break;
case '/' :
if(Input > Start && Input[-1] == '*')
{
*Rover++ = ')';
++Input;
}
else if(Input[1] != '*')
*Rover++ = *Input++;
else
{
*Rover++ = '(';
++Input;
}
break;
default:
*Rover++ = *Input++;
}
if((unsigned)(Input - Start) > Len)
break;
}
*Rover = '\0';
return Note;
}
/* OpcodesInsert() - insert the entire opcode table.
*
* We try to emit this in a commented, understandable way.
*/
static
void OpcodesInsert(FILE* Output, TParseTables* Tables)
{
TSymbol* Symbol;
BLC_OPCODE* Opcodes;
int IP, iSelect, NSelect, iRule, Reduced, iSymbol;
int NSymbols;
int TermSymTabSize, NonTermSymTabSize, EntryTabSize, SelectTabSize, RuleTabSize;
int OpcodesOffset, SelectOffset;
Dump("OpcodesInsert()\n");
Opcodes = Tables->Opcodes;
assert(Opcodes != NULL);
IP = 0;
/* Emit header information */
TermSymTabSize = Load16(Opcodes, &IP);
Emit(Output, DEC16, TermSymTabSize, "[%4d] terminal symbol table size", TermSymTabSize);
NonTermSymTabSize = Load16(Opcodes, &IP);
Emit(Output, DEC16, NonTermSymTabSize, "[%4d] nonterminal symbol table size", NonTermSymTabSize);
EntryTabSize = Load16(Opcodes, &IP);
Emit(Output, DEC16, EntryTabSize, "[%4d] entry table size", EntryTabSize);
SelectTabSize = Load16(Opcodes, &IP);
Emit(Output, DEC16, SelectTabSize, "[%4d] selection table size", SelectTabSize);
RuleTabSize = Load16(Opcodes, &IP);
Emit(Output, DEC16, RuleTabSize, "[%4d] rule opcode table size", RuleTabSize);
NSelect = SymbolListCount(Tables->LLNonTerms);
// assert(NSelect == Load16(Opcodes, &IP));
// Emit(Output, DEC16, NSelect, "%d LL nonterminals", NSelect);
// Start = Load16(Opcodes, &IP);
// Emit(Output, HEX16, Start, "0x%04X: address of entry point", Start);
/* emit terminal symbol table */
fprintf(Output, "/* Terminal symbol table */\n");
while(IP < 10 + TermSymTabSize)
{
Emit(Output, DEC8, Opcodes[IP], "[%4d] '%s'", Opcodes[IP], Opcodes+IP+1);
++IP;
for(;;)
{
int Col;
fprintf(Output, " ");
for(Col = 0; Col < 4; ++Col)
{
if(isalnum(Opcodes[IP]))
fprintf(Output, "'%c', ", Opcodes[IP]);
else
fprintf(Output, "%2d, ", Opcodes[IP]);
if(Opcodes[IP++] == 0)
break;
}
fprintf(Output, "\n");
if(Opcodes[IP-1] == 0)
break;
}
if(Opcodes[IP] == 0)
break;
}
assert(Opcodes[IP] == 0);
Emit(Output, DEC8, Opcodes[IP], "sentinel byte");
++IP;
fprintf(Output, "/* Nonterminal symbol table */\n");
iSymbol = 0;
while(IP < 10 + TermSymTabSize + NonTermSymTabSize)
{
fprintf(Output, "/* [%d] %s */\n", iSymbol++, Opcodes+IP);
for(;;)
{
int Col;
fprintf(Output, " ");
for(Col = 0; Col < 4; ++Col)
{
if(isalnum(Opcodes[IP]))
fprintf(Output, "'%c', ", Opcodes[IP]);
else
fprintf(Output, "%2d, ", Opcodes[IP]);
if(Opcodes[IP++] == 0)
break;
}
fprintf(Output, "\n");
if(Opcodes[IP-1] == 0)
break;
}
if(Opcodes[IP] == 0)
break;
}
assert(Opcodes[IP] == 0);
Emit(Output, DEC8, Opcodes[IP], "sentinel byte");
++IP;
fprintf(Output, "/* entry table */\n");
Symbol = SymbolStart();
for(iRule = 0; iRule < RuleCount(Symbol); ++iRule)
{
Emit(Output, HEX16, Opcodes[IP] | (Opcodes[IP+1]<<8), "%s",
SymbolStr(SymbolListGet(Symbol->Rules[iRule]->Symbols, 0)));
IP += 2;
}
while(IP < 10 + TermSymTabSize + NonTermSymTabSize + EntryTabSize)
{
}
fprintf(Output, "/* selection table */\n");
/* emit LLSELECT bodies */
SelectOffset = IP;
for(iSelect=0; iSelect < NSelect; ++iSelect)
{
TSymbol* NonTerm = SymbolListGet(Tables->LLNonTerms, iSelect);
assert(NonTerm != NULL);
fprintf(Output, "/*0x%04X:%9s LLSELECT body for '%s' */\n", IP-SelectOffset, "", SymbolStr(NonTerm));
IP = EmitSelectBody(Output, Opcodes, IP);
}
OpcodesOffset = IP;
/* emit actual opcodes */
fprintf(Output, "\n/*0x%04X:%9s Begin opcodes */\n", IP, "");
/* generate opcodes for each unique rule */
for(iRule = 0; iRule < Tables->NRules; ++iRule)
{
unsigned Address;
int iProdItem, iSymbol;
TRule* Rule = Tables->Rules[iRule];
SYMBOLS Symbols = Tables->RuleSymbols[iRule];
Reduced = FALSE; /* have not performed a reduction for this rule yet */
NSymbols = SymbolListCount(Rule->Symbols);
fprintf(Output, "/*[0x%04X] ", IP - OpcodesOffset);
for(iSymbol=0; (Symbol=SymbolListGet(Symbols, iSymbol)) != NULL; ++iSymbol)
fprintf(Output, "%s%s", iSymbol?" | ":"", SymbolStr(Symbol));
fprintf(Output, " -> ");
SymbolListDump(Output, Rule->Symbols, " ");
fprintf(Output, " */\n");
for(iProdItem = 0; iProdItem < NSymbols; ++iProdItem)
{
TSymbol* Symbol = SymbolListGet(Rule->Symbols, iProdItem);
if(SymbolGetBit(Symbol, SYM_TERMINAL))
{
assert(Opcodes[IP] == BLCOP_MATCH);
Emit(Output, HEX8, Opcodes[IP++], "MATCH %s", SymbolStr(Symbol));
Emit(Output, DEC8, Opcodes[IP++], NULL);
if(Symbol == SymbolFind(EOFToken))
{
assert(Opcodes[IP] == BLCOP_HALT);
Emit(Output, HEX8, Opcodes[IP++], "HALT");
Reduced = TRUE;
}
// IP = Store8(Opcodes, IP, BLCOP_MATCH);
// IP = Store8(Opcodes, IP, Symbol->Value);
}
else if(SymbolIsAction(Symbol))
{
int FinalAction;
assert(Rule->RuleId < 255);
assert(iProdItem < 255);
FinalAction = FALSE;
if(iProdItem == NSymbols-1)
FinalAction = TRUE;
else if(Rule->TailRecursive && iProdItem == NSymbols-2)
FinalAction = TRUE;
if(FinalAction) /* if it's the final action */
{
assert(Opcodes[IP] == BLCOP_ACTRED);
Emit(Output, HEX8, Opcodes[IP++], "BLCOP_ACTRED %s", ActionNote(Symbol->Action));
Emit(Output, HEX8, Opcodes[IP++], " rule#");
Emit(Output, HEX8, Opcodes[IP++], " <argcount>");
Reduced = TRUE;
}
else
{
assert(Opcodes[IP] == BLCOP_ACTION8);
Emit(Output, HEX8, Opcodes[IP++], "BLCOP_ACTION8 %s", ActionNote(Symbol->Action));
Emit(Output, HEX8, Opcodes[IP++], " rule#");
Emit(Output, HEX8, Opcodes[IP++], " <argcount>");
}
assert(Rule->RuleId < 255);
assert(iProdItem < 255);
}
else if(SymbolListContains(Tables->LLNonTerms, Symbol)) /* non-terminal */
{
int iSymbol = SymbolListContains(Tables->LLNonTerms, Symbol);
if(RuleCount(Symbol) > 1)
{
if(Symbol->Name.Text[0] == '`') /* if a tail recursive rule... */
{
Emit(Output, HEX8, Opcodes[IP++], "BLCOP_TAILSELECT %s", SymbolStr(Symbol));
Emit(Output, HEX8, Opcodes[IP++], NULL);
Reduced = TRUE;
}
else
Emit(Output, HEX8, Opcodes[IP++], "BLCOP_LLSELECT %s", SymbolStr(Symbol));
Address = Opcodes[IP++];
Address |= (Opcodes[IP++] << 8);
Emit(Output, HEX16, Address, NULL);
// Emit(Output, HEX16, Opcodes[IP++] | (Opcodes[IP++]<<8), NULL);
// IP = Store8(Opcodes, IP, BLCOP_LLSELECT);
// IP = Store16(Opcodes, IP, Symbol->SelectOffset);
}
/* else, only 1 rule to choose from, so just transfer control to that rule! */
else
{
// int iRule = AddRule(Tables, Symbol->Rules[0]);
Emit(Output, HEX8, Opcodes[IP++], "BLCOP_CALL %s", SymbolStr(Symbol));
Address = Opcodes[IP++];
Address |= (Opcodes[IP++] << 8);
Emit(Output, HEX16, Address, NULL);
// IP = Store8(Opcodes, IP, BLCOP_CALL);
// IP = MarkPatch(IP, iRule);
}
assert(iSymbol>0);
}
else // else, it's an operator trigger
fprintf(stderr, "watch out: we don't handle LR(0) yet!\n");
}
if(!Reduced)
{
Emit(Output, HEX8, Opcodes[IP], "BLCOP_REDUCE %d", Opcodes[IP+1]);
++IP;
Emit(Output, DEC8, Opcodes[IP++], "");
// IP = Store8(Opcodes, IP, BLCOP_REDUCE);
// IP = Store8(Opcodes, IP, NSymbols);
}
}
#if 0
while(IP < Tables->NOpcodes)
IP = EmitOpcode(Output, Opcodes, IP);
#endif
Dump("OpcodesInsert() returns\n");
}
#if 0
void TransitionsInsert(FILE* Output, TParseTables* Tables)
{
TSymbol* NonTerm;
int NNonTerms, NTokens;
int iToken, iNonTerm, iTransition;
NNonTerms = SymbolListCount(Globals.NonTerms);
iTransition = 1;
for(iNonTerm = 0; iNonTerm < NNonTerms; ++iNonTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iNonTerm);
if(NonTerm->OperatorTrigger || NonTerm == SymbolStart())
continue;
fprintf(Output, "/*[%3d] %.*s %*.s*/\n", iTransition,
NonTerm->Name.TextLen, NonTerm->Name.Text,
MAX(1,32-NonTerm->Name.TextLen), "");
fprintf(Output, " ");
NTokens = SymbolListCount(NonTerm->InputTokens);
for(iToken = 0; iToken < NTokens; ++iToken)
{
TSymbol* Input;
/* get next input token that produces a transition for this non-terminal */
Input = SymbolListGet(NonTerm->InputTokens, iToken);
assert(Input != NULL);
assert(Tables->Transitions[iTransition] == Input->Value);
if(Input->Name.Text[0] == '\'')
{
if(Input->Name.TextLen == 3 && isgraph(Input->Name.Text[1]))
fprintf(Output, "%.*s,", Input->Name.TextLen, Input->Name.Text);
else
fprintf(Output, "%d,", Tables->Transitions[iTransition]);
}
else
fprintf(Output, "%.*s,", Input->Name.TextLen, Input->Name.Text);
++iTransition;
fprintf(Output, "%d, ", Tables->Transitions[iTransition++]);
}
assert(Tables->Transitions[iTransition] == EolSymbol->Value);
fprintf(Output, "%.*s,", EolSymbol->Name.TextLen, EolSymbol->Name.Text);
++iTransition;
fprintf(Output, "\n");
}
}
#endif
#if 0
void ProductionsInsert(FILE* Output, TParseTables* Tables)
{
TSymbol* NonTerm;
int NNonTerms, NSymbols;
int iRule, iNonTerm, iProduction;
NNonTerms = SymbolListCount(Globals.NonTerms);
iProduction = 0;
for(iNonTerm = 0; iNonTerm < NNonTerms; ++iNonTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iNonTerm);
/* if it belongs to operator precedence grammar */
if(NonTerm->OperatorTrigger || NonTerm == SymbolStart())
continue; /* then skip it */
/* for each non-terminal production */
for(iRule = 0; iRule < NonTerm->NRules; ++iRule)
{
int TokenOrOffset, iSymbol;
TRule* Rule;
assert(NonTerm->Rules != NULL);
Rule = NonTerm->Rules[iRule];
assert(Rule != NULL);
NSymbols = SymbolListCount(Rule->Symbols);
fprintf(Output, "/*[%3d]%.*s%*.s: ", iProduction,
NonTerm->Name.TextLen, NonTerm->Name.Text,
MAX(1,12-NonTerm->Name.TextLen), "");
if(NSymbols == 0)
fprintf(Output, "<epsilon>");
else
SymbolListDump(Output, Rule->Symbols, " ");
fprintf(Output, " */\n");
assert(iProduction + NSymbols + 2 <= Tables->ProductionsSize);
fprintf(Output, " ");
/* for each symbol on RHS of production */
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
{
TSymbol* Symbol = SymbolListGet(Rule->Symbols, iSymbol);
assert(Symbol != NULL);
if(Symbol->Type == TERMINAL)
TokenOrOffset = Symbol->Value;
else
TokenOrOffset = Symbol->TransitionOffset;
fprintf(Output, "%d,", Tables->Productions[iProduction++]);
}
/* emit end-of-list separator */
fprintf(Output, " %.*s,", EolSymbol->Name.TextLen, EolSymbol->Name.Text);
++iProduction;
/* emit stack size */
fprintf(Output, " %d, ", Tables->Productions[iProduction++]);
/* emit action# associated with this production */
if(Tables->Productions[iProduction])
fprintf(Output, " %d", Tables->Productions[iProduction]);
else
fprintf(Output, " BLC_NOACTION");
++iProduction;
if((iRule+1) == NonTerm->NRules && (iNonTerm+1) == NNonTerms)
;
else
fprintf(Output, ",\n");
}
}
}
#endif
#if 0
void ProductionsInsert(FILE* Output, TParseTables* Tables)
{
TSymbol* NonTerm;
int NNonTerms, NSymbols;
int iRule, iNonTerm, iProduction;
int ByteOffset;
MAP SymMap;
SymMap = MapCreate(NULL);
NNonTerms = SymbolListCount(Globals.NonTerms);
ByteOffset = 0;
iProduction = 0;
for(iNonTerm = 0; iNonTerm < NNonTerms; ++iNonTerm)
{
NonTerm = SymbolListGet(Globals.NonTerms, iNonTerm);
/* if it belongs to operator precedence grammar */
if(NonTerm->OperatorTrigger || NonTerm == SymbolStart())
continue; /* then skip it */
/* for each non-terminal production */
for(iRule = 0; iRule < NonTerm->NRules; ++iRule)
{
int TokenOrOffset, iSymbol;
TRule* Rule;
assert(NonTerm->Rules != NULL);
Rule = NonTerm->Rules[iRule];
assert(Rule != NULL);
NSymbols = SymbolListCount(Rule->Symbols);
fprintf(Output, "/*[%3d]%.*s%*.s: ", iProduction,
NonTerm->Name.TextLen, NonTerm->Name.Text,
MAX(1,12-NonTerm->Name.TextLen), "");
if(NSymbols == 0)
fprintf(Output, "<epsilon>");
else
SymbolListDump(Output, Rule->Symbols, " ");
fprintf(Output, " */\n");
assert(iProduction + NSymbols + 2 <= Tables->ProductionsSize);
fprintf(Output, " ");
/* for each symbol on RHS of production */
for(iSymbol = 0; iSymbol < NSymbols; ++iSymbol)
{
TSymbol* Symbol = SymbolListGet(Rule->Symbols, iSymbol);
assert(Symbol != NULL);
if(Symbol->Type == TERMINAL)
fprintf(Output, "BLCOP_MATCH, %d,\t/* MATCH %s */\n",
Symbol->Value, Symbol->Name.Text, 4);
else
TokenOrOffset = Symbol->TransitionOffset;
fprintf(Output, "%d,", Tables->Productions[iProduction++]);
}
/* emit end-of-list separator */
fprintf(Output, " %.*s,", EolSymbol->Name.TextLen, EolSymbol->Name.Text);
++iProduction;
/* emit stack size */
fprintf(Output, " %d, ", Tables->Productions[iProduction++]);
/* emit action# associated with this production */
if(Tables->Productions[iProduction])
fprintf(Output, " %d", Tables->Productions[iProduction]);
else
fprintf(Output, " BLC_NOACTION");
++iProduction;
if((iRule+1) == NonTerm->NRules && (iNonTerm+1) == NNonTerms)
;
else
fprintf(Output, ",\n");
}
}
}
#endif
/* ProgramInsert() - insert the user program code.
*
* This is whatever follows the second '%%' in the source.
*/
static
void ProgramInsert(FILE* Output, TParseTables* Tables)
{
ARGUNUSED(Tables);
if(Globals.ProgramSection.Type == TK_PROGRAM)
{
fputs(Globals.ProgramSection.Text, Output);
}
}
static
void ActionsInsert(FILE* Output)
{
int iAction;
SymIt NonTerm = SymItNew(Globals.Actions);
for(iAction=0; SymbolIterate(&NonTerm); ++iAction)
{
TAction* Action = NonTerm.Symbol->Action;
if(Action)
{
const char* Rover;
const char* End;
printf("Action %d has length %d\n", Action->Number, Action->Action.TextLen);
fprintf(Output, " case %d :\n {\n", Action->Number);
Rover = Action->Action.Text;
End = Rover + Action->Action.TextLen;
for(; Rover < End; ++Rover)
{
if(*Rover == '$')
{
if(*++Rover == '$')
fprintf(Output, "(State.ReturnValue)");
else if(isdigit(*Rover))
{
int Offset = 0;
while(isdigit(*Rover))
{
Offset = Offset * 10 + (*Rover - '0');
++Rover;
}
--Rover; /* correct overshoot */
fprintf(Output, "/*Offset=%d,ArgCount=%d*/(State.VSP[%d])", Offset, Action->ArgCount, (Offset-Action->ArgCount)-1);
}
else
fprintf(Output, "$%c", *Rover);
}
else
fprintf(Output, "%c", *Rover);
}
// fprintf(Output, "%.*s", Action->Action.TextLen, Action->Action.Text);
fprintf(Output, "\n }\n");
fprintf(Output, "break;\n");
}
}
}
static
int MatchAlias(const char* Input, const char* Name, size_t Len)
{
size_t NameLen = strlen(Name);
return (Len == NameLen) && !strncmp(Input, Name, NameLen);
}
const char* DoInsert(FILE* Output, TParseTables* Tables, const char* Rover)
{
size_t NameLen;
const char* Name;
Name = ++Rover;
while(*Rover != '@')
{
assert(isalpha(*Rover));
++Rover;
}
NameLen = Rover - Name;
assert(NameLen > 0);
Dump("DoInsert(%.*s)\n", NameLen, Name);
if(!strncmp(Name, "VERSION", strlen("VERSION")))
VersionInsert(Output);
else if(MatchAlias(Name, "ACTIONS", NameLen))
ActionsInsert(Output);
else if(MatchAlias(Name, "FILENAME", NameLen))
FilenameInsert(Output);
else if(MatchAlias(Name, "TIMESTAMP", NameLen))
TimestampInsert(Output);
else if(MatchAlias(Name, "TYPEDEFS",NameLen))
TypeDefsInsert(Output, Tables);
else if(MatchAlias(Name, "TOKENDEFS",NameLen))
TokenDefsInsert(Output);
else if(!strncmp(Name, "VALIDTOKENS", strlen("VALIDTOKENS")))
ValidTokensInsert(Output, Tables);
else if(!strncmp(Name, "NEXTSTATESIZE", strlen("NEXTSTATESIZE")))
fprintf(Output, "%d", Tables->LLRows.Size);
#if 0
else if(!strncmp(Name, "RULEJUMPSIZE", strlen("RULEJUMPSIZE")))
fprintf(Output, "%d", Tables->RuleOffsets.Size);
else if(!strncmp(Name, "RULEJUMPS", strlen("RULEJUMPS")))
RuleJumpsInsert(Output, Tables);
else if(!strncmp(Name, "SELECTJUMPSIZE", strlen("SELECTJUMPSIZE")))
fprintf(Output, "%d", Tables->SelectOffsets.Size);
else if(!strncmp(Name, "SELECTJUMPS", strlen("SELECTJUMPS")))
SelectJumpsInsert(Output, Tables);
else if(!strncmp(Name, "NEXTSTATES", strlen("NEXTSTATES")))
NextStatesInsert(Output, Tables);
#endif
else if(!strncmp(Name, "OPCODESIZE", strlen("OPCODESIZE")))
fprintf(Output, "%d /* 0x%04X */", Tables->NOpcodes, Tables->NOpcodes);
else if(!strncmp(Name, "OPCODES", strlen("OPCODES")))
OpcodesInsert(Output, Tables);
else if(!strncmp(Name, "PROGRAM", strlen("PROGRAM")))
ProgramInsert(Output, Tables);
else if(!strncmp(Name, "VALTOKSIZE", strlen("VALTOKSIZE")))
fprintf(Output, "%d", Tables->LLColumns.Size);
#if 0
else if(!strncmp(Name, "TRANSSIZE", strlen("TRANSSIZE")))
TransSizeInsert(Output, Tables);
else if(!strncmp(Name, "PRODSSIZE", strlen("PRODSSIZE")))
ProdsSizeInsert(Output, Tables);
else if(!strncmp(Name, "TRANSITIONS", strlen("TRANSITIONS")))
TransitionsInsert(Output, Tables);
else if(!strncmp(Name, "PRODUCTIONS", strlen("PRODUCTIONS")))
ProductionsInsert(Output, Tables);
#endif
// else if(!strncmp(Name, "OPCODETYPEDEF", strlen("OPCODETYPEDEF")))
// fprintf(Output, "typedef int OPCODETYPEDEF;\n");
else
ErrorExit(ERROR_BAD_NAME_IN_TEMPLATE, "Can't happen. Bad name in template: '%.*s'\n",
NameLen, Name);
return Rover + 1;
}
int GenerateC(FILE* Output, TParseTables* Tables)
{
const char* Rover = Template;
Dump("GenerateC() begins (opcode table = %d bytes)\n", Tables->NOpcodes);
while(*Rover)
if(*Rover == '@')
Rover = DoInsert(Output, Tables, Rover);
else
fputc(*Rover++, Output);
Dump("GenerateC() returns\n");
return TRUE;
}
|
100siddhartha-blacc
|
gen_c.c
|
C
|
mit
| 33,450
|
#ifndef COMPUTE_H_
#define COMPUTE_H_
void MarkNullable(void);
void MarkEmpty(void);
void MarkLeftRecursive(void);
void RewriteGrammar(void);
void ClearFirstFollow(void);
void ComputeFirst(void);
void ComputeFollow(void);
void ComputeEndsWith(void);
void ComputeLLTable(void);
void ComputeOperators(void);
#endif /* COMPUTE_H_ */
|
100siddhartha-blacc
|
compute.h
|
C
|
mit
| 379
|